Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django problem with creating instance of model basing on pre_delete signal
I have a model which represents the archives. Once the main advert has been deleted, it's archives version is being created to later view. I wanted to acomplish it basing on signals. I believe my code is correct but for some reason it does not launch signals. signals.py from django.db.models.signals import post_save, post_delete, pre_delete from django.dispatch import receiver from core.models import Advert, Archive @receiver(pre_delete, sender=Advert) def archive_advert(sender, instance, **kwargs): archives = Archive.objects.create(user=instance.user, title=instance.title, category=instance.category, price=instance.price, quantity=instance.quantity, description=instance.description, image=instance.image) models class Archive(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) title = models.CharField(blank=True, null=True, max_length = 100) category = models.CharField(blank=True, null=True, max_length = 3) price = models.FloatField(blank=True, null=True) quantity = models.IntegerField(blank=True, null=True) description = models.TextField(blank=True, null=True, max_length = 1000) posted = models.DateTimeField(blank=True, null=True) image = models.ImageField(blank=True, upload_to="advert_images") apps.py class CoreConfig(AppConfig): name = 'core' def ready(self): import core.signals -
How to create a form for dealing with multiple django model objects
So I have a model Post with the following definition: class Post(models.Model): post_body = models.TextField() user = models.ForeignKey( to=User, on_delete=models.CASCADE ) published = models.BooleanField( default=False ) schedule = models.DateTimeField( default=timezone.now ) I have created a form in HTML template allowing the user to select the posts he want to send to another website or social media account. Like so: <form> <table class="table table-hover"> <thead> <tr> <th scope="col">Select</th> <th scope="col">Post Body</th> <th scope="col">Published?</th> <th scope="col">Schedule (Editable)</th> </tr> </thead> <tbody> {% for post in posts %} <tr> <td> <div class="form-group"> <input type="checkbox" value="{{ post.id }}"> </div> </td> <td>{{ post.post_body }}</td> <td>{{ post.published }}</td> <td> <div class="form-group"> <input type="datetime-local" class="form-control" name="schedule" value="{{ post.schedule|date:"Y-m-d\TH:i" }}"> </div> </td> </tr> {% endfor %} </tbody> </table> <button class="btn btn-primary" type="submit">Post</button> </form> I want to create a Form in the forms.py in order to process this information (i.e. know which all posts were selected) and then perform further actions (calling other APIs in order to publish these to other sites), also since the field schedule is editable, I want to be able to save that as well. Please help as I cannot think of a possible form for this. -
Inherit models whith seperate primary key in django model
I have a abstract model which I want all of my models inherit from it: from django.db import models class Audit(models.Model): create_date = models.DateTimeField(auto_now_add=True) last_modify_date = models.DateTimeField(auto_now=True) create_by = models.CharField(null=True, max_length=50) last_modify_by = models.CharField(null=True, max_length=50) class Meta: abstract: True now fro example I have two models: from general.AuditableModel import Audit class Province(Audit): name = models.CharField(max_length=30) class Meta: db_table = 'province_v2' verbose_name_plural = _('provinces') verbose_name = _('province') class City(Audit): province_id = models.ForeignKey('address.Province', on_delete=models.CASCADE, related_name='cities') name = models.CharField(max_length=30) class Meta: db_table = 'city_v2' verbose_name_plural = _('cities') verbose_name = _('city') in my database it makes tables like this: create table province_v2 ( audit_ptr_id integer not null primary key references general_audit deferrable initially deferred, name varchar(30) not null ); create table city_v2 ( audit_ptr_id integer not null primary key references general_audit deferrable initially deferred, name varchar(30) not null, province_id_id integer not null references province_v2 deferrable initially deferred ); create index city_v2_province_id_id_12975070 on city_v2 (province_id_id); but I want my models have independent id integer primary key without abstract table, now it made general_audit table -
Django - 'WSGIRequest' object has no attribute 'get' when rendering the form
I'm working on a question management system. I have two different types of questions which make things a little more complicated. I have a page where every question is listed and I'm making the question detail page. When I access this page, I have this 'WSGIRequest' object has no attribute 'get' error. My models : import uuid from django.db import models from django.contrib.auth.models import User class Question_Num(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) num_question = models.IntegerField(default=0) question = models.TextField(max_length=1000, unique=True) reponse = models.IntegerField(default=0) class Meta: verbose_name = 'Question' verbose_name_plural = 'Questions' def __str__(self): return f'Question n°{self.num_question}' class QCM(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) num_question = models.IntegerField(default=0) question = models.TextField(max_length=1000, unique=True) choix_1 = models.CharField(max_length=200, unique=True, default='') choix_2 = models.CharField(max_length=200, unique=True, default='') choix_3 = models.CharField(max_length=200, unique=True, default='') choix_4 = models.CharField(max_length=200, unique=True, default='') class Meta: verbose_name = 'QCM' verbose_name_plural = 'QCM' def __str__(self): return f'QCM n°{self.num_question}' My forms : from django import forms from django.contrib.auth.models import User from .models import Question_Num, QCM class Modif_QCM(forms.ModelForm): num_question = forms.IntegerField( initial = QCM.num_question ) question = forms.IntegerField( initial = QCM.question ) choix_1 = forms.IntegerField( initial = QCM.choix_1 ) choix_2 = forms.IntegerField( initial = QCM.choix_2 ) choix_3 = forms.IntegerField( initial = QCM.choix_3 ) choix_4 = forms.IntegerField( initial = … -
I'm Working on a django project where i extended the auth_user table for add the operators and this will give an error
MY HTML CODE === This is my html code for adding the operator in the database {% extends 'Adminside/master.html' %} {% block content %} <div class="col-md-12"> <!-- general form elements --> <div class="card card-primary"> <div class="card-header"> <h3 class="card-title">Add Operator</h3> </div> <!-- /.card-header --> <!-- form start --> <form role="form" action="{% url 'addoperator' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="card-body"> <div class="form-group"> <label for="exampleInputEmail1">Name</label> <input type="text" class="form-control" id="exampleInputname" name="name" placeholder="Enter Your Name"> </div> <div class="form-group"> <label for="exampleInputEmail1">Email address</label> <input type="email" class="form-control" id="exampleInputEmail1" name="email" placeholder="Enter email"> </div> <div class="form-group"> <label for="exampleInputPassword1">Password</label> <input type="password" class="form-control" id="exampleInputPassword1" name="password" placeholder="Password"> </div> <div class="form-group"> <label for="exampleInputEmail1">Address</label> <input type="text" class="form-control" id="exampleInputaddress" name="address" placeholder="Enter Your Address"> </div> <div class="form-group"> <label for="exampleInputEmail1">Phone Number</label> <input type="text" class="form-control" id="exampleInputnumber" name="number" placeholder="Enter Your Phone Number"> </div> <div class="col-sm-6"> <!-- radio --> <div class="form-group clearfix"> <div class="icheck-primary d-inline"> <input type="radio" id="radioPrimary1" name="gender" value="Male" checked=""> <label for="radioPrimary1"> Male </label> </div> <div class="icheck-primary d-inline"> <input type="radio" id="radioPrimary2" value="Female" name="gender"> <label for="radioPrimary2"> Female </label> </div> <div class="icheck-primary d-inline"> <input type="radio" id="radioPrimary3" disabled=""> Gender </label> </div> </div> </div> <div class="form-group"> <label for="exampleInputFile">Image Upload</label> <div class="input-group"> <div class="custom-file"> <input type="file" name="userimage" class="form-control" required> </div> </div> </div> <div class="form-group"> <label for="exampleInputFile">Document Upload</label> <div class="input-group"> <div class="custom-file"> <input type="file" … -
Remove title of the data from Django Rest Frame
I have this models.py class Topologies(models.Model): topology = models.CharField(max_length=50) component = models.CharField(max_length=50) latency = models.FloatField() capacity = models.FloatField() time = models.CharField(blank=True, max_length=10) def __str__(self): return self.topology And this serializers.py class Last10TopoTime(serializers.ModelSerializer): class Meta: model = models.Topologies fields = ('latency', 'capacity') The output is this: [ { "latency": 19.218, "capacity": 0.048 }, { "latency": 19.218, "capacity": 0.054 }, { "latency": 19.219, "capacity": 0.054 } ] But I only want this [ { 19.218, 0.048 }, { 19.218, 0.054 }, { 19.219, 0.054 }, I don't have any articles on this can anyone suggest anyway show that I can do it. -
How to get the data from BoundField?
I would like to get the number 2 from my BoundField object, that's problematic because it is not iterable or doesnt support indexing. <BoundField value=2 errors=None> Can someone please help? -
Searching through a ManyToManyField in Django
I have a model that contains a ManyToManyField. It looks like this.. applicable_events = models.ManyToManyField(Event) I am trying to basically search using something like this: if 'Video' in prop.applicable_events.all(): print("here") But it isn't fully working as I expected. I want it to search that applicable_event (which is another model). The applicable_event model contains a field named 'name' which I am trying to search against. If I do something like this print(prop.applicable_events.all().filter(name=cur_event)) It prints <QuerySet [<Event: Video Sign In Started>]> So basically I am trying to find out if the string 'Video' is contained in that. -
Unexpected Behaviour of PasswordResetView which sends too many consecutive emails
My Django 3.0 Project is using the default Django Reset Password view, so in my url.py: path('password_reset', auth_views.PasswordResetView.as_view(), name='password_reset') There is a strange behaviour because when I request reseting the password, the view sends a lot of emails to the email address I introduced (let´s say 37 emails). This happened regardless using SendGrid or AWS SES, so something wrong is happening in the view. I investigated and I think the problem is in the PasswordResetForm class which the view uses to send emails. Such form has a get_users() method, which return matching user(s) who should receive a reset, it retrieves all the active users who provided the email. def get_users(self, email): """Given an email, return matching user(s) who should receive a reset. This allows subclasses to more easily customize the default policies that prevent inactive users and users with unusable passwords from resetting their password. """ email_field_name = UserModel.get_email_field_name() active_users = UserModel._default_manager.filter(**{ '%s__iexact' % email_field_name: email, 'is_active': True, }) return ( u for u in active_users if u.has_usable_password() and _unicode_ci_compare(email, getattr(u, email_field_name)) ) The save() method of the form sends an email to each of the users returned by get_users(). I think my problem is that I registered several users … -
change the language attrib in HTML tag based on user's language Django Wagtail
how to change the language attribute <html class="no-js" lang="en"> in HTML tag based on user's language dynamically? in .. Django & #Wagtail templates -
Django 3 - What is the method for creating list and Django detail view urls with stub or slug of name and not int of pk?
In Django 3 what is the correct method for creating list and detail view with friendly urls with either a stub or slug of name and not a int of pk? stub versus slug for list and detail view I want to be able to use list and detail view with a readable urls more friendly then number or int? I tried a variety of tutorials but they all seam to use different methods like url, path, re path, include, reverse, reverse lazy etc. I have been able to do using urls patterns something like this but is the int method r'^starwars/(?P<pk>\d+)$' I am trying to do something like this. it will be using a template inheriting from a base template for both list and detail views. ``` http://127.0.0.1:8000/ #as homepage http://127.0.0.1:8000/starwars/ #as list of series http://127.0.0.1:8000/starwars/the_mandalorian/ # page is detailed view with list of the mandalorian characters ``` Instead of http://127.0.0.1:8000/ #as homepage http://127.0.0.1:8000/starwars/ #as list of series http://127.0.0.1:8000/starwars/1/ path to templates Project_folder |_ starwars |_ templates |_ starwars |_ starwars_base.html starwars_detail.html starwars_list.html ------ Settings.py ------- I add the template directories here like this in two places # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = … -
django : url change depends on model exist
I'd like to make user access to page depends on model exist. and I use CBV. Do I have to control views? or urls? Is FBV only way to control url? How can I control user access url? hope kindly help me. i'd like to control for example:(as you know, this is invalid syntax. hope you know what i'm saying.) from django.urls import path from . import views, models app_name = "papers" urlpatterns = [ path( "memberagreement/<int:preassociation_pk>/", {% if models.MemberAgreement.association.get(pk=preassociaion_pk) is not NULL %} views.member_agreement_detail_vc.as_view(), {% else %} views.member_agreement_create_vc.as_view(), {% endif %} name="member_agreement_vc", ) ] -
Django 3.0 images: Unable to display images in template
I have model named Book in models.py file. And based on this model, a view has been created to display images as products. Which renders books(products) on shop.html template. Problem is that i am unable to get their cover images which are saved across each publishers id who is seller of those books. This is code of shop.html (in which i am trying to display image). <div class="container mt-4"> <div class="row"> {% for b in books|slice:":10" %} <div class="col-lg-2 col-md-3 col-sm-4"> <div class="book-card"> <div class="book-card__book-front"> <img src={{MEDIA_URL}}{{b.cover.url}} alt="book-image"> </div> </div> <div class="book-card__title"> {{ b.title }} </div> </div> </div> </div> {% endfor %} </div> </div> This is the model in which i am putting covers of books against publisher's ids (names) def book_cover_path(instance, filename): return os.path.join( "covers", instance.publisher.user.username, str( instance.pk) + '.' + filename.split('.')[-1] ) class Book(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField('Title', max_length=255) authors = models.ManyToManyField(Author, related_name='books_written') publisher = models.ForeignKey(Publisher, on_delete=models.DO_NOTHING, related_name='books_published') price = models.DecimalField('Price', decimal_places=2, max_digits=10) description = models.TextField('Description') upload_timestamp = models.DateTimeField('Uploading DateTime', auto_now_add=True) categories = models.ManyToManyField(Category, related_name='book_category') cover = models.ImageField(upload_to=book_cover_path, null=True,blank=True) class Meta: unique_together = ('title', 'publisher') get_latest_by = '-upload_timestamp' This is view in views.py def shop(req): bookz = Book.objects.order_by('title') var = {'books': bookz, 'range': 10} … -
ModelChoiceFilter is throwing error in Django
I have following Filter class. class CallSummaryFilterSet(filters.FilterSet): ringing_mobile_number = filters.ModelChoiceFilter(queryset=CallSummary.objects.all(),method='filter_mobile_number') class Meta: model = CallSummary fields = ('caller', 'callee') def filter_mobile_number(self, queryset, name, value): queryset = queryset.filter(Q(caller=value) | Q(callee=value)) return queryset Request Format :- http://127.0.0.1:8000/call-summaries/?ringing_mobile_number=1234567890 it's throwing following error. {'ringing_mobile_number': [ErrorDetail(string='Select a valid choice. That choice is not one of the available choices.', code='invalid_choice')]} -
applying google-oauth2 in django
i am trying to use google auth2 and is struck at the type of request the function is demanding in django i.e try: # Specify the CLIENT_ID of the app that accesses the backend: idinfo = id_token.verify_oauth2_token(token, requests.Request(), CLIENT_ID) # Or, if multiple clients access the backend server: # idinfo = id_token.verify_oauth2_token(token, requests.Request()) # if idinfo['aud'] not in [CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]: # raise ValueError('Could not verify audience.') if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']: raise ValueError('Wrong issuer.') # If auth request is from a G Suite domain: # if idinfo['hd'] != GSUITE_DOMAIN_NAME: # raise ValueError('Wrong hosted domain.') # ID token is valid. Get the user's Google Account ID from the decoded token. userid = idinfo['sub'] this is from the https://developers.google.com/identity/sign-in/web/backend-auth where request is from the following function var xhr = new XMLHttpRequest(); xhr.open('POST', 'https://yourbackend.example.com/tokensignin'); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = function() { console.log('Signed in as: ' + xhr.responseText); }; xhr.send('idtoken=' + id_token); shall i pass it directly or just the token value -
Accessing a property coming from manytomany field
This is my models.py: class Role(models.Model): type= models.CharField(max_length=30) class Profile(models.Model): role = models.ManyToManyField(Role, blank=True) def is_composer(self): return self.role['Composer'] This is my view.py: from .models import Profile, Role def profiles_filtered(request, type): model = Profile if type == 'composers': queryset = Profile.objects.filter(is_composer = True) My urls.py: urlpatterns = [ path('profiles/<str:type>/', views.profiles_filtered, name="profiles"), ] And my template: <li><a href="{% url 'profiles' 'composers' %}"> Composers</a></li> When I click on the link, I get to /profiles/composers/, which should list all the profiles containing the role 'Composer'. I get a FieldError at /profiles/composers/ Cannot resolve keyword 'is_composer' into field. The Role type contains many roles, one of which is 'Composer'. How can I list only the profiles which contain a 'Composer' role? -
django Error: AttributeError: 'ModelFormOptions' object has no attribute 'private_fields'
I have two tables 1. intake request (this table has a field that should be shown as drop down values from the 2nd table) 2. drop down list (this table contains the list of values for all sorts of fields. Which is what I want to show as drop down in various forms) List Category List Of Value Choices technology_used spark technology_used oracle country USA country Canada So for a technology_used in intake request I need to show only spark and oracle in drop down For country field in intake request I need to show only USA and Canada **models.py** class DropDownList(models.Model): list_category = models.CharField(max_length=20) list_value = models.CharField(max_length=50) def __str__(self): return self.list_value class Meta: managed = True db_table = 'domain_DropDownList' class DatastoreIntakeRequest(models.Model): user = models.ForeignKey(User, default=1, on_delete=models.CASCADE) technology_used = models.ForeignKey(DropDownList, default=1, on_delete=models.SET_NULL, null=True) def __str__(self): return self.therapeutic_area def get_absolute_url(self): return reverse('domain:intake_detail', kwargs={'pk': self.pk}) #excluding country class here **forms.py** class DatastoreIntakeRequestForm(forms.ModelForm): class Meta: model = DatastoreIntakeRequest fields = ['technology_used',] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['technology_used'].queryset = DropDownList.objects.none() if 'technology_used' in self.data: try: list_cat = 'technology_used' self.fields['technology_used'].queryset = DropDownList.objects.filter(list_category=list_cat).order_by('list_value') except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty City queryset **views.py** class DatastoreIntakeRequestCreateView(CreateView): form_class = … -
Why do I get TemplateDoesNotExist for only 1 template?
I have a form I would like to display on a html template named query_page.html but I keep getting the TemplateDoesNot exist error even though I have the template. I don't think it is related to my settings.py as my 10 other templates work perfectly. I think it might be related to how I am mapping in urls.py class QueryView(FormView): form_class = QueryForm template_name = 'query_page.html' def form_valid(self, form): print(form.cleaned_data) return super().form_valid(form) urlpatterns = [ path('', views.index, name='index'), path('patient_new/', views.patient_new, name='patient_new'), path('location_new/', views.location_new, name='location_new'), path('location_list/', views.location_temps, name='location_list'), re_path('patient/(?P<pk>\d+)$', views.PatientDetailView.as_view(), name='patient_detail'), re_path('location/(?P<pk>\d+)$', views.LocationDetailView.as_view(), name='location_detail'), re_path('patient/(?P<pk>\d+)/edit/$', views.PatientUpdateView.as_view(), name='patient_edit'), re_path('my_form/$', require_POST(views.MyFormView.as_view()), name='my_form_view_url'), re_path('patient/(?P<pk>\d+)/remove/$', views.PatientDeleteView.as_view(), name='patient_remove'), #re_path('patient/(?P<pk>\d+)/query/$', views.profile_search, name='query'), re_path('patient/(?P<pk>\d+)/query/$', views.QueryView.as_view(), name='query'), re_path('location/(?P<pk>\d+)/edit/$', views.LocationUpdateView.as_view(), name='location_edit'), re_path('location/(?P<pk>\d+)/remove/$', views.LocationDeleteView.as_view(), name='location_remove'), ] it is this line: re_path('patient/(?P<pk>\d+)/query/$', views.QueryView.as_view(), name='query') Link to the form: <p><a class="btn btn-primary" href="{% url 'query' pk=patient.pk %}">Query</a></p> -
CrispyError at /register/ |as_crispy_field got passed an invalid or inexistent field
My Error traceback: (I get this whenever I open my Register page) Environment: Request Method: GET Request URL: http://127.0.0.1:8000/register/ Django Version: 3.0.4 Python Version: 3.7.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap4', 'crispy_forms', 'django_tables2', 'staffplanner.apps.StaffplannerConfig', 'accounts.apps.AccountsConfig'] 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'] Template error: In template D:\ng_projects\Planner-5\NG\staffplanner\templates\staffplanner\match.html, error at line 0 |as_crispy_field got passed an invalid or inexistent field 1 : 2 : {% load static %} 3 : {% load crispy_forms_tags %} 4 : {% load render_table from django_tables2 %} 5 : <!DOCTYPE html> 6 : <html lang="en"> 7 : <head> 8 : <meta charset="UTF-8"> 9 : <meta name="viewport" content="width=device-width, initial-scale=1.0"> 10 : <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> Traceback (most recent call last): File "C:\Users\noori\Envs\planner\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\noori\Envs\planner\lib\site-packages\django\core\handlers\base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\noori\Envs\planner\lib\site-packages\django\core\handlers\base.py", line 143, in _get_response response = response.render() File "C:\Users\noori\Envs\planner\lib\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "C:\Users\noori\Envs\planner\lib\site-packages\django\template\response.py", line 83, in rendered_content return template.render(context, self._request) File "C:\Users\noori\Envs\planner\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "C:\Users\noori\Envs\planner\lib\site-packages\django\template\base.py", line 171, in render return self._render(context) File "C:\Users\noori\Envs\planner\lib\site-packages\django\template\base.py", line 163, in _render return self.nodelist.render(context) File "C:\Users\noori\Envs\planner\lib\site-packages\django\template\base.py", line 936, in render bit = node.render_annotated(context) File "C:\Users\noori\Envs\planner\lib\site-packages\django\template\base.py", … -
Django model translation using gettext
There is little information on why to use gettext to translate content from the database what are its advantages and implications? Why hardly anyone talks about this? I see more information about: django-modeltranslation django-parler django-hvad Would it be more scalable to use django-vinaigrette? or are there some other alternatives? -
error during trying to connect to my server via ssh , can not connect to my vps server vis ssh
i've build a website using django and apache but today it suddenly raised an error when i try to open my website it show only Apache2 Ubuntu Default Page This is the default welcome page used to test the correct operation of the Apache2 server after installation on Ubuntu systems. It is based on the equivalent page on Debian etc .. before worked fine for about 9 month , i tried to connect to the server via ssh terminal ssh username@my_ip_address but it raised this error @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY! Someone could be eavesdropping on you right now (man-in-the-middle attack)! It is also possible that a host key has just been changed. The fingerprint for the ECDSA key sent by the remote host is SHA256:the_key Please contact your system administrator. Add correct host key in /home/username/.ssh/known_hosts to get rid of this message. Offending ECDSA key in /home/username/.ssh/known_hosts:2 ECDSA host key for my_ip has changed and you have requested strict checking. Host key verification failed. and i run this command ssh-keygen -R my_ip and the output Host 51.83.98.146 found: line 2 /home/username/.ssh/known_hosts updated. Original contents retained … -
how to update the date?
when i'm updating the except all fields then updating well when i adding date field its not updating any data... plz let me know why.... forms.py class EmployeeForm(ModelForm): class Meta: model = Employee fields = "__all__" widgets = { 'edob': DateInput(), 'egender': forms.RadioSelect(), } models.py class Employee(models.Model): eid = models.CharField(max_length=20) ename = models.CharField(max_length=100) eemail = models.EmailField() econtact = models.CharField(max_length=15) esalary = models.CharField(max_length=100) egender = models.CharField(max_length=20, choices=G_CHOICES, default='male') edob = models.DateField() def __str__(self): return self.ename class Meta: db_table = "employee" update.html <div class="form-group row"> <label class="col-sm-2 col-form-label">Employee DOB:</label> <div class="col-sm-4"> <input type="text" name="edob" id="id_edob" required maxlength="15" value="{{ employee.edob }}" /> </div> how to solve this didn't getting .... -
Django Rest Framework,Filtering objects based on Forignkey relationship
I have a simple Blog app where anyone can add post and comment to post. Comments have forignkey relationship with Post. When I select url patch posts/<post id>/comments it shows all comments instead of the comments from related posts. All other CRUD functions works fine with the project. The Git Link :https://github.com/Anoop-George/DjangoBlog.git The problem occurs in view.py where comment object unable to filter comments which are related to specific posts. class CommentListCreate(APIView): def get(self, request,pk): **comment = Comment.objects.filter()** # I need filter here serializer = CommentSerializers(comment, many=True) return Response(serializer.data) -
Django Rest Framework - Django ORM instance.delete() doesn't delete the instance...?
I have the following API delete view: @action(detail=True, methods=['delete'], permission_classes=[IsAuthenticatedViaJWTCookie]) def delete(self, request, pk=None, *args, **kwargs): queryset = self.get_queryset().get(id=pk) if queryset.user == request.user: queryset.delete() return Response(status=status.HTTP_204_NO_CONTENT) else: response = standardized_json_error_response( message='Artwork Object Could Not Be Deleted', data=[] ) return Response(data=response, status=status.HTTP_401_UNAUTHORIZED) When calling this view from an axios.delete request, I can see that the delete request is being made, and hitting the endpoint. All good so far. Yet, in the listing API view, the target instance to be deleted is still being listed. Doesn't matter how many times that endpoint is refreshed, or how long I wait. What is worse still, is when I call that endpoint again using axios.delete in the front end, for a second time, the record is then permanently deleted? Has anyone experienced such odd behaviour before with Django, or could this be a third party issue? *I have installed django-cleanup...? -
Heroku Debug Flag not stopping django debugging
I'm currently have Django project in heroku but I tried to stop the debug mode but unfortunately it's not working. First I tried to stop it from settings.py DEBUG=False DEBUG = os.environ.get('DEBUG', False) both not helping tried also to set env variable heroku config:set DEBUG=False heroku config:unset DEBUG both also not helping I tried to assign wrong value the debug in settings.py for testing which caused to crash the deployment. Hopefully some one can help with this.