Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Chancing the form message(validation) even if fromis valid if recaptcha is not passed
I'm using a form mixin to check a recaptcha after, the form fields were checked: class FormRecaptchaView(ABC): def form_valid(self, form): recaptcha_response = self.request.POST.get('g-recaptcha-response') data = { 'secret': RECAPTCHA_SECRET_KEY, 'response': recaptcha_response } r = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data) result = r.json() if result['success']: return super().form_valid(form) else: messages.error(self.request, 'Invalid reCAPTCHA. Please try again.') return self.form_invalid(form) The mixin I used, to inherit from it: class ContactView(FormRecaptchaView, FormView): success_message = 'Your message has been sent' .... def form_valid(self, form): response = super().form_valid(form) # call the email function send_email_async(context=cont_email) return valid The issue is that because the form is valid (but recaptcha is not) the success message is still added an appear, and also other code is execute(in the example above the send_email_async) So I want if recaptcha is not valid, to remove 'success message' and avoid executing other code. -
how to display company name instead of email address while sending password reset email in django
how to display name instead of email address.I am using PasswordResetView and i have configured this email in settings.py.When i just use only email address in EMAIL_HOST_USER then it works fine but after i changed like this to display name then it is not working.How can i solve this settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = "CompanyName <company@gmail.com>" EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = '587' -
Problems with migrations after moving to server. 'ProgrammingError: relation "django_content_type" already exists -
I've migrated across to a server environment, and finally got everything working. The django project is rendering properly, but there seems to be a big problem with the migrations/database. When I try and run migrations, I'm getting this error, which is affecting other things (like scripts I use to populate the project) File "/home//.virtualenvs/versal/lib/python3.7/site-packages/djang o/db/backends/utils.py", line 83, in _execute return self.cursor.execute(sql) django.db.utils.ProgrammingError: relation "django_content_type" already exists (versal) 06:18 ~/Versal/versal (master)$ Failing row contains (null, contenttypes, 0001_initial, 2019-04-29 06:11:02.087041+0 I tried to cleanup migrations and run them again, but this hasn't worked, as this is what 'showmigrations' shows. accounts [ ] 0001_initial admin [ ] 0001_initial [ ] 0002_logentry_remove_auto_add [ ] 0003_logentry_add_action_flag_choices auth [ ] 0001_initial [ ] 0002_alter_permission_name_max_length [ ] 0003_alter_user_email_max_length [ ] 0004_alter_user_username_opts [ ] 0005_alter_user_last_login_null [ ] 0006_require_contenttypes_0002 [ ] 0007_alter_validators_add_error_messages [ ] 0008_alter_user_username_max_length [ ] 0009_alter_user_last_name_max_length blog [ ] 0001_initial [ ] 0002_auto_20190225_1221 [ ] 0003_auto_20190225_1251 contenttypes [ ] 0001_initial [ ] 0002_remove_content_type_name core [ ] 0001_initial [ ] 0002_auto_20190331_1730 [ ] 0003_auto_20190404_0920 curate [ ] 0001_initial [ ] 0002_item_video [ ] 0003_set [ ] 0004_auto_20190424_1620 [ ] 0005_item_tags django_comments [ ] 0001_initial [ ] 0002_update_user_email_field_length [ ] 0003_add_submit_date_index podcast [ ] 0001_initial [ ] 0002_remove_episode_order [ … -
How do I save base64 image from html5 canvas as ImageField in Django?
On my form I have an ImageField as well as a hidden CharField to accept an image as base64. When a user selects an image on the frontend form my js script on the frontend auto resizes the image as a canvas then sets the generated dataUrl as the content for the CharField. I would like that when the form is submitted I can convert the base64 text to an image and override the saving of the original Image in the ImageField so that the decoded base64 image is saved in it's place instead (filename and all). I have followed several tutorials online which have lead me to the code below. I have overwritten the clean() function in my forms.py so that the base64 text is decoded into a PIL Image. Now I would like to set it in place of the actual ImageField's content so that it is saved and handled as if the base64 decoded image was the file sent in POST. Other answers suggest saving the decoded base64 image manually using a with open() command but that approach opens other headaches. Especially since Django already handles image renaming if an image is submitted with a name that … -
No Such Table when Running Django (2.0.13) Tests with SQLite3 Database
When attempting to run Django (version 2.0.13) automated testing a test isn throwing an operational error, "no such table". The table exists in my production database, and there exists migration code to create the table in the migration modules, however when attempting to create an instance of a model based on the table I get django.db.utils.OperationalError: no such table: test_table The testSettings.py looks as such: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'default', 'TEST_NAME': 'default', 'USER': 'u', 'PASSWORD': 'p', 'HOST': 'localhost', 'PORT': '', 'TIME_ZONE': 'Australia/Sydney' }, } MIGRATION_MODULES = { ... 'app': 'app.test.test_migration_app_0001_initial', } And it exists in the migration file for testing: migrations.CreateModel( name='Test_Table', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=30, unique=True)), ], ), ... migrations.AddField( model_name='test_subtable', name='test_table', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='test', to='app.test_table'), ), Of possible note, the database table is using the INNODB engine. -
how to create a like button, which a user can only like once in django website?
i want to create a fully functional like button, when can be like only once by a user . i have already create a like button but that is not i am looking for, my current like button can be liked as many times as user want to like . enter code here ##models.py class Images(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='images_created', on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True, null=True, blank=True) message_likes = models.IntegerField(default=0) objects = InheritanceManager() ##views.py def like_treasure(request): treasure_id = request.POST.get('treasure_id', None) message_likes = 0 if (treasure_id): treasure = Postsms.objects.get(id=int(treasure_id)) if treasure is not None: message_likes = treasure.message_likes + 1 treasure.message_likes = message_likes treasure.save() return HttpResponse(message_likes) ## $ $('button').on('click', function(event){ event.preventDefault(); var element = $(this); $.ajax({ url : '/like_treasure/', type : 'POST', data : { treasure_id : element.attr("data-id")}, success : function(response){ element.html(' ' + response); } }); }); ##html <button style="background-color: red" id ="likes" data-id="{{foo.id}}" class="btn btn-mini glyphicon glyphicon-heart" type="button" > {% if foo.message_likes > 0 %} {{ foo.message_likes }} {% endif %} -
I am working on dates on django, Is there a way to compare the rendered date on html to check if it is less than 3 days left on current date
I have this code where it normally displays all of the number of rows on database. Is there a way to compare the returned date(Promised Date) to javascript or jquery so i can highlight all of the dates that are less than 3 days from the today's date. Thanks <div class="container"> <table id="requirement_table" class="table table-bordered table-hover table-sm" style="width:100%"> <thead> <tr> <th>Applicant Name</th> <th>Requirement</th> <th>Remarks</th> <th>Promised Date</th> <th>Completed</th> </tr> </thead> <tbody> {% for req in app_requirements %} <tr> <th>{{ req.applicant }}</th> <th>{{ req.requirement }}</th> <th>{{ req.remarks }}</th> <th>{{ req.date_promised }}</th> <th>{{ req.completed }}</th> </tr> {% endfor %} </tbody> </table> </div> -
How can I pass my filtered queryset from listview to another view that uses PDFTemplateView for printing?
I'm trying to print using wkhtmltopdf with a queryset from a django-filters filtered listview. I can't use post because my list.html template is not a form. filter_set = [] class IssueListView(TemplateListView): def get_context_data(self, **kwargs): context = super(IssueListView, self).get_context_data(**kwargs) global filter_set filter_set = [] for issue in context['object_list']: filter_set.append(issue.pk) return context class IssuePDF(ReportTemplateView): report_title = 'Complaints Register' model = Issue object_list = Issue.objects.all() def get_context_data(self, **kwargs): context = super(IssuePDF, self).get_context_data(**kwargs) context['report_title'] = self.report_title context['object_list'] = self.model.objects.all() global filter_set context['object_list'] = Issue.objects.filter(pk__in=filter_set) return context This works because I am currently using a global variable but the queryset changes everytime I print in the Production Server. -
wsgi:alert No such file or directory: mod_wsgi (pid=XXXX): Couldn't bind unix domain socket '/usr/local/opt/httpd/logs/wsgi.xxxxx.11.1.sock'
After upgrading Apache-httpd from 2.4.33 to 2.4.39 in Mac OS (Mojave), I am facing this issue: [wsgi:alert] No such file or directory: mod_wsgi (pid=XXXX): Couldn't bind unix domain socket '/usr/local/opt/httpd/logs/wsgi.xxxxx.11.1.sock' Please let me know what configuration needs to be added in httpd.conf to mitigate this issue. As the server is not reachable with 503 error. -
How to make detail view in django html?
How can i show the data based on its id ? This is how i passed the id into url {% for i in result %} <h4><a href="/novel/{{i.docno}}">{{i.title}}</a></h4> {% endfor %} now, if i click one item, i got the url like this http://localhost:8000/novel/11 for now, this is the views.py i've write def novel_page(request, id): return render(request, 'novel.html') and the urls.py is path('novel/<int:id>', views.novel_page, name='novel'), and i want to show the detail of item with id like what i passed to url For example, if i click the data with id is 11, so the sistem will display all of data based on id 11. Thanks -
How to fix 'if form.is_valid():' in Django Python?
Im creating a simple blog with Django. But I got this faile all the time: if form.is_valid(): Here is my views.py from django.shortcuts import render from django.http import HttpResponseRedirect from .forms import RegistrationForm def register(request): form = forms.RegistrationForm() if request.method == 'POST': form = forms.RegistrationForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/') return render(request, 'pages/register.html', {'form': form}) -
ProgrammingError: relation "taggit_tag" does not exist
Following the guide for this package: https://github.com/kamilgregorczyk/OrderFood I get the error django.db.utils.ProgrammingError: relation "taggit_tag" does not exist when trying to migrate. Full traceback: Traceback (most recent call last): File "/home/michael/projects/OrderFood/orderums/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "taggit_tag" does not exist LINE 1: ...ECT "taggit_tag"."name", "taggit_tag"."name" FROM "taggit_ta... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/michael/projects/OrderFood/orderums/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/michael/projects/OrderFood/orderums/lib/python3.6/site-packages/django/core/management/__init__.py", line 337, in execute django.setup() File "/home/michael/projects/OrderFood/orderums/lib/python3.6/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/michael/projects/OrderFood/orderums/lib/python3.6/site-packages/django/apps/registry.py", line 116, in populate app_config.ready() File "/home/michael/projects/OrderFood/orderums/lib/python3.6/site-packages/django/contrib/admin/apps.py", line 23, in ready self.module.autodiscover() File "/home/michael/projects/OrderFood/orderums/lib/python3.6/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) File "/home/michael/projects/OrderFood/orderums/lib/python3.6/site-packages/django/utils/module_loading.py", line 50, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/michael/projects/OrderFood/apps/restaurant/admin.py", line 7, in <module> from apps.restaurant.forms import MealForm File "/home/michael/projects/OrderFood/apps/restaurant/forms.py", line 8, in <module> class MealForm(forms.ModelForm): File "/home/michael/projects/OrderFood/apps/restaurant/forms.py", line … -
i want to create a profile of each usertype and create a many to many relationship with their respective shcedule
I want player and coach to have their own profile with their own extra fields. when scheduling, player enrolled in specific training should have a coach with the respective specialty class UserType(models.Model): user =models.OneToOneField(User, on_delete=models.CASCADE) USER_TYPE = ( (1, 'Player'), (2, 'Coach'), ) user_type = models.IntegerField(choices=USER_TYPE) class Schedule(models.Model): Schedule_List = ( (1, '10:00 – 11:00'), (2, '11:00 – 12:00'), (3, '12:00 – 13:00'), (4, '13:00 – 14:00'), (5, '14:00 – 15:00'), ) schedule = models.IntegerField(choices=Schedule_List, null=True) user = models.ManyToManyField(User) class Coach(models.Model): usertype = models.OneToOneField(UserType, on_delete=models.CASCADE) specialty = models.CharField(max_length=20) picture = models.ImageField(upload_to = '', default = '') #return the coach' name def __str__(self): return str(self.user) class Player(models.Model): usertype = models.OneToOneField(UserType, on_delete=models.CASCADE) enrolled_training=models.CharField(max_lenght=20) #return the players' name def __str__(self): return str(self.user) -
how to develop a drop down menu in django based on a foreign key field in a model
I am developing a Django form to upload files. the form is based on a model(files). The model(files) has a foreign key field (repo_id). This repo_id is the primary key in the Repository model. I want users to be able to choose which repo_id to put the file in. I need to insert a value to this field using a drop-down list in the form. in the HTML template, the dropdown list is showing as "Repository object(repo_id)" I have developed the two models (files and repository) in models.py, views.py, forms.py and HTML template following a tutorial. The form is working and it saves data in the database table as well. I want to update the drop-down menu only to show indicator names in the repository model, not a repository object. Here are my codes. models.py from django.db import models # Create your models here. class Repository(models.Model): source = models.TextField(db_column='source', blank=True, null=True) # Field name made lowercase. indicator = models.TextField(db_column='indicator', blank=True, null=True) # Field name made lowercase. key_aspect = models.TextField(db_column='key_aspect', blank=True, null=True) category = models.TextField(db_column = 'category') table_id = models.TextField(db_column='table_id', blank=True, null=True) data_returning = models.TextField(db_column='data_returning', blank=True, null=True) data_source = models.TextField(db_column='data_source', blank=True, null=True) value = models.TextField(db_column='value', blank=True, null=True) # Field name made … -
How to delete a comment using web sockets?
I have seen a lot of articles talk about using the web sockets in creating a chat app. But my question is can i delete something like comment or post using the web sockets too ? if the answer is yes please provide your answer with an example. -
Reading uploaded csv file into pandas dataframe
I am uploading a CSV file and wish to load it into a pandas dataframe. I have a problem loading the file into my view. The warning message is sent to the template which signifies that the file was not sent to the view. Here is my view: def showReadUploadedView(request, **kwargs): context = {} test_file = request.GET.get(u'testFile') df = pd.read_csv(test_file) context = {'df': df} if not test_file: messages.warning(request, f'No file to process! Please upload a file to process.') return render(request, 'tasks/up_load.html', context) Here is my template: <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="file" class="form-control-file mt-1 mb-1" id="testFile"> <button class="btn btn-danger btn-sm mb-3 mt-1" type="submit">Process this</button> <a href="{% url 'upload-task' task.id %}" class="btn btn-danger btn-sm mb-3 mt-1">Process Data</ </form> -
redirect requirement - LetsEncrypt
My understanding is that in order to setup Let's encrypt on webfaction, the following has to be satisfied: You need to make sure the URI /.well-known/acme-challenge/ is not being redirected by your application code. Is there a specific setting in django that I should look for or set to ensure that this redirect isn't happening? Thanks! -
Getting a TypeError at / 'function' object is not iterable
I keep getting this error ('function' object is not iterable) after having added a new def function in my .views file, any thoughts on what the problem could be? Here's my views.py function: def FilterView(request): qs = Product.objects.all() ptag = request.GET.get('ptag') if ptag == 'on': qs = qs.filter(ptag='') qs = filter(request) context = { 'queryset': qs } return render(request, "partials/search_form.html", context) And in my urls: from search.views import HomeView, FilterView urlpatterns = [ url(r'^$', HomeView.as_view(), FilterView), ] Thanks so much! -
Paginating a context inside a DetailView in Django
I have an Asset Detail View that displays data from another two models, Tenant and Service. asset\views.py class AssetMultipleDetailView(LoginRequiredMixin, UserPassesTestMixin, DetailView): model = Asset context_object_name = 'asset' template_name = 'asset/asset_multiple_detail.html' def test_func(self): asset_multiple = self.get_object() if self.request.user == asset_multiple.owner: return True return False def get_context_data(self, **kwargs): context = super(AssetMultipleDetailView, self).get_context_data(**kwargs) context['tenants'] = Tenant.objects.filter(asset=context['asset']).order_by('created') context['services'] = Service.objects.filter(asset=context['asset']).order_by('created') return context I would like to paginate the data that's in context['tenants] and context['services'] and I do not know how to achieve this. I have done this in their own ListViews using paginated_by and got it working without any issues. I simply would like to know how to paginate a context in DetailView. Thank you in advance. -
How to successfully process a POST request in Django
I am new to Django and web development in general. I have a Course model in models.py. I essentially want to add courses on the frontend. I would use a POST to the server. I am just a little confused on if I am doing things correctly, or if I am missing something. I have created an AddCourseForm class in order to try and handle this. models.py class Course(models.Model): id = models.AutoField(primary_key=True) name = CharField(max_length=100) class Project(models.Model): id = models.AutoField(primary_key=True) desc = CharField(max_length=150) name = CharField(max_length=50) storyboard_file_path = TextField() storyboard_completed = BooleanField(default=False) filming_complete = BooleanField(default=False) audio_complete = BooleanField(default=False) production_complete = BooleanField(default=False) aggregation_complete = BooleanField(default=False) video_file_path = TextField() final_review_complete = BooleanField(default=False) course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name="projects", null=True, blank=True) serializer.py class Meta: model = Project fields = ('id', 'desc', 'name', 'storyboard_file_path', 'storyboard_completed', 'filming_complete', 'audio_complete', 'production_complete', 'aggregation_complete', 'video_file_path', 'final_review_complete', 'course') def create(self, validated_data): instance = self.Meta.model(**validated_data) instance.save() return instance def update(self, instance, validated_data): for attr, value in validated_data.items(): setattr(instance, attr, value) instance.save() return instance class CouserSerializer(serializers.ModelSerializer): projects = ProjectSerializer(many=True, read_only=True) class Meta: model = Course fields = ('id', 'name', 'projects') def create(self, validated_data): instance = self.Meta.model(**validated_data) instance.save() return instance forms.py class Meta: model = Course fields = [ 'name' ] views.py queryset = … -
Sending django queryset with annotate to my rest api
i have two simple models with random data about phones. class Phone(models.Model): name = models.CharField(max_length=200) description = models.CharField(max_length=400) image = models.ImageField(upload_to='phone_img/', max_length=255, null=True, blank=True ) slug_phone = models.SlugField(blank=True) class Price(models.Model): price = models.DecimalField(max_digits=6, decimal_places=2) date = models.DateField(null=True, blank=True) phone = models.ForeignKey(Phone, on_delete=models.CASCADE) market = models.ForeignKey(Market, on_delete=models.CASCADE) I am able to send simple data via data the REST_framwork to my API. views.py class SnippetList(generics.ListCreateAPIView): queryset = Price.objects.all() serializer_class = PriceSerializer serializers.py class PriceSerializer(serializers.ModelSerializer): class Meta: model = Price fields = ('id', 'phone', 'price', 'date', 'market', ) phone = serializers.StringRelatedField() market = serializers.StringRelatedField() Now i wanted to use the annotate() method with the Min() function in a QuerySet. I wanted to display the minimum price of each phone. So i tried something like this: views.py from django.db.models import Min <....> class SnippetList(generics.ListCreateAPIView): queryset = Price.objects.all() serializer_class = PriceSerializer def get_queryset(self): min_price = Phone.objects.annotate(Min('price__price')) return min_price of course this did not work. i followed along the server errors messages and ended with this: serializers.py from rest_framework import serializers from market.models import Price, Phone class PriceSerializer(serializers.ModelSerializer): class Meta: model = Price fields = ('id', 'phone', 'price', 'date', 'market') class Meta: model = Phone fields = ('name', 'phone', 'market', ) phone = serializers.StringRelatedField() market = … -
djangoproject.sock file filed (2: No such file or directory) while connecting to upstream found in nginx error log
I have been trying to troubleshoot some 500 and 502 bad gateway issues on my production site for some time now. I looked in the nginx log files and found there to be errors which I can't seem to find any help for. Here is the error log for nginx: 2019/04/28 20:52:10 [crit] 921#921: *1 connect() to unix:/pathto/django/project/projectname.sock failed (2: No such file or directory) while connecting to upstream, client: x.x.x.x, server: example.com, request: "GET / HTTP/1.1", upstream: "http://unix:/pathto/django/project/projectname.sock:/", host: "example.com" 2019/04/28 20:53:55 [error] 921#921: *17 upstream prematurely closed connection while reading response header from upstream, client: x.x.x.x, server: example.com, request: "POST /games/ HTTP/1.1", upstream: "http://unix:/pathto/django/project/projectname.sock:/x/", host: "example.com", referrer: "http://example.com/x/" 2019/04/28 20:55:57 [error] 921#921: *17 upstream prematurely closed connection while reading response header from upstream, client: x.x.x.x, server: example.com, request: "POST /games/ HTTP/1.1", upstream: "http://unix:/pathto/django/project/projectname.sock:/x/", host: "example.com", referrer: "http://example.com/x/" I have tried increasing the timeout duration in both nginx as well as gunicorn with no luck. Some of the operations on my site take a couple of minutes to complete due to several API requests and I believe it may be timing however I am not entirely sure. My sites-available nginx file: server { listen 80; server_name example.com; location = … -
ValueError: No module named 'notmigrations' during unit tests
I have django application 2.1.7 with django-tenant plugin (creating schemas in the database for saas). My problem is unit testing. I run the command: python manage.py test --settings=project.settings_test and I'm getting a error: ImportError: No module named 'notmigrations' My code in settings_test file from .settings_base import * class DisableMigrations(object): def __contains__(self, item): return True def __getitem__(self, item): return 'notmigrations' MIGRATION_MODULES = DisableMigrations() -
How to save data django foreign key with forms.modelform on view with a post request?
I am facing a problem with foreignkey. I can save the data by request post with the foreignkey. without the foreignkey I can save a data by a request post but it's not what I need. I need to post the data from a request post and after I got the data from the admin area I want to choose the foreignkey. I have a 4 models. 1 models: class Realtor(models.Model): first_name = models.CharField(_("First name"), max_length=255) last_name = models.CharField(_("Last name"), max_length=255) photo = models.ImageField(upload_to='photos_realtors/%Y/%m/%d/') description = models.TextField(blank=True) country = models.CharField(max_length=250, choices=COUNTRIES) types = models.CharField(max_length=60, choices=TYPES) phone = PhoneNumberField(unique=True) email = models.EmailField(max_length=50) is_mvp = models.BooleanField(default=False) is_published = models.BooleanField(default=True) hire_date = models.DateTimeField(default=datetime.now, blank=True) Realtor_ID = models.CharField(max_length=120, default=get_ref_id_re, unique=True, editable=False) def __str__(self): return '{} {}'.format(self.first_name, self.last_name) def get_full_name(self): return '{} {}'.format(self.first_name, self.last_name) 2 models: class Notary(models.Model): first_name = models.CharField(_("First name"), max_length=255) last_name = models.CharField(_("Last name"), max_length=255) photo = models.ImageField(upload_to='photos_notary/%Y/%m/%d/') description = models.TextField(blank=True) country = models.CharField(max_length=250, choices=COUNTRIES) types = models.CharField(max_length=60, choices=TYPES) phone = PhoneNumberField(unique=True) email = models.EmailField(max_length=50) is_mvp = models.BooleanField(default=False) is_published = models.BooleanField(default=False) hire_date = models.DateTimeField(default=datetime.now, blank=True) Notary_ID = models.CharField(max_length=120, default=get_ref_id_no, unique=True, editable=False) def __str__(self): return '{} {}'.format(self.first_name, self.last_name) def get_full_name(self): return '{} {}'.format(self.first_name, self.last_name) 3 models: class FinanceBankHouse(models.Model): name = models.CharField(max_length=200) photo = … -
Validate if user is authenticated and if is post author
how i can validate if user is authenticated and is post author. my model.py: class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) my views.py: def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('created_date ') return render(request, 'blog/post_list.html', {'posts': posts}) def post_detail(request, pk): posts = get_object_or_404(Post, pk=pk) return render(request, 'blog/post_detail.html', {'post': posts}) @login_required def post_new(request): if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.published_date = timezone.now() post.save() return redirect('post_detail', pk=post.pk) else: form = PostForm() return render(request, 'blog/post_edit.html', {'form': form}) @login_required def post_edit(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = PostForm(request.POST, instance=post) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.published_date = timezone.now() post.save() return redirect('post_detail', pk=post.pk) else: form = PostForm(instance=post) return render(request, 'blog/post_edit.html', {'form': form}) @login_required def post_remove(request, pk): post = get_object_or_404(Post, pk=pk) post.delete() return redirect('post_list') and my html: % extends 'blog/base.html' %} {% block content %} <div class="post"> {% if post.published_date %} <div class="date"> {{ post.published_date }} </div> {% else %} <a class="btn btn-default" href="{% url 'post_publish' pk=post.pk %}">Publish</a> {% endif %} {% if user.is_authenticated %} <a class="btn btn-default" href="{% url 'post_edit' pk=post.pk %}"> <span class="glyphicon glyphicon-pencil"></span></a> <a class="btn btn-default" …