Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add tags when add a page to a known parent programatically in wagtail?
I would like to create programatically a sub page for a known parent. here is the code. parent_page = Page.objects.get(title='index02').specific news_page = BlogPage( title = 'title test 08', slug = 'title_test_08', body='Something pleasant to hear.', intro="desc", ) parent_page.add_child(instance=news_page) news_page.save() It works, but I added tags = '[tag01,tag02]' in news_page , It failed to add tags, Could sb tell me how to add tags? thanks. -
help_text - Django Crispy Forms
I want to add help text to the form: investigation_title = forms.CharField( error_messages={'required': 'Please provide an Investigation Title'}, help_text = 'Help text...', ) def __init__(self, *args, **kwargs): super(InvestigationForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = True self.helper.form_class = 'form-horizontal' ... self.helper.help_text_inline = True ... But like this the help text is render below the field box. How to move the help text to the right side of the field box, position as it shows in the picture in the red rectangle? -
Django. How to save serialized and validated data?
I have a Car model with name, model and serial number fields. In which the combination of the name and model fields must be unique. I am using serializers.ModelSerializer from rest_framework and validator UniqueTogetherValidator. validators = [ UniqueTogetherValidator( queryset=models.Car.objects.all(), fields=['name', 'model'] ) ] The database already has an entry {'name': 'one', 'model': '13', 'serial number': 99}. I want to add a list of cars: data = [{'name': 'one', 'model': '13', 'serial number': 99}, {'name': 'two', 'model': '3', 'serial number ': 98}, {' name ':' three ',' model ':' 1 ',' serial number ': 949}] For this I use: serializer = CarSerializer (data = data) if serializer.is_valid (): serializer.save () I understand that is_valid () will return False. In the passed list, only one record is not valid, how to save valid data from the passed list? -
django "<User: user556>" needs to have a value for field "id" before this many-to-many relationship can be used
I'm trying to save a M2M object ( set it to a default value which is the one with id = 1 ). The problem I'm getting the following error: "<User: user556>" needs to have a value for field "id" before this many-to-many relationship can be used. I looked at previous feeds that covered the same error but no one explained when it happens in the form_valid function as it happened to me My code is as follows : def form_valid(self,form): instance = form.instance instance.groups.set(1) instance.save() return super(UserCreateView,self).form_valid(form) -
Simplest way to lock the model instances and its related object in Django
To avoid the concurrency I am trying to put a lock on Django's model's instances. Orders class Orders(BaseModel): created_by = models.ForeignKey(User, on_delete=models.PROTECT, null=False, blank=False) property = models.ForeignKey(Properties, on_delete=models.PROTECT, null=False, blank=False) units = models.IntegerField(null=False, blank=False) buy_price_per_unit = models.FloatField(null=True, blank=True) sell_price_per_unit = models.FloatField(null=True, blank=True) order_type = models.ForeignKey(OrderType, on_delete=models.PROTECT, null=False, blank=False) order_status = models.ForeignKey(OrderStatus, on_delete=models.PROTECT, null=False, blank=False) fluctuation_upper_limit = models.FloatField( null=False, blank=False) #IN PERCENT fluctuation_lower_limit = models.FloatField( null=False, blank=False) #IN PERCENT order_trade_fee = models.FloatField( null=False, blank=False) #IN PERCENT tax_percent = models.FloatField( null=False, blank=False) #IN PERCEN In the above model I have a ForeignKey field property referencing to the model Properties. Furthermore, I also have a model PropertyOwners which has a ForeignKey field property referencing to the model Properties. The query I am using is - Orders.objects .select_for_update() .exclude(created_by=created_by) .values('id', 'property', 'units', 'created_by', 'sell_price_per_unit', 'order_status') .filter(property=order_obj.property, order_type__name=SELL, order_status__in=[PARTIALLY_COMPLETED[1], OPEN[1]], sell_price_per_unit__lte=order_price) .order_by('sell_price_per_unit') You can see I have used select_for_update() to lock the Orders instances fetched by this query. However, I also want to lock the instance of model Properties to which all these order are pointing and the instances of the PropertyOwners where the field property and created_by from Orders is equal to the fields property and owner from PropertyOwners for each order. The query … -
Integrating Django Rest Framework with OneLogin
I am working on a backend built on Django and Django Rest Framework. I have been trying to integrate with Onelogin for a little bit and I do not manage to do it. SAML: It seems that python3-saml is mainly build for traditional Django using sessions. Which is not a very REST like behavior. I could not find a way to make it work with DRF. Nor could I find a package that fits my needs. I will continue working on OpenId connect but I am wondering if it is possible to use Django Rest Framework with python3-saml? Thank you for you help -
mixins Django how to enable staff-user post, edit, delete permission in html template
I am using mixins in my views for restrict unauthenticated user to access my blog-post page, edit-page and delete-page. Right now only admin user can access those page but I also give permission to staff user for access those page. see the picture: still now my staff user get 404 error when trying to access those page. here is my code: #views.py class blog_publish_view(PermissionRequiredMixin,CreateView): raise_exception = True permission_required = "blog_add_blog" model = Post form_class = BlogPost template_name = "blog_post.html" #fields = ['title','author','body'] class blog_update_view(PermissionRequiredMixin,UpdateView): raise_exception = True permission_required = "blog_change_blog" model = Post template_name = "blog_update_post.html" form_class = BlogPost class blog_delete_view(PermissionRequiredMixin,DeleteView): raise_exception = True permission_required = "blog_delete_blog" model = Post template_name = "delete_blog_post.html" success_url = reverse_lazy('blog') #my html page for post blog: {% if user.is_authenticated %} <div class="container"> <h1>Publish Blog</h1> <form method="POST"> {% csrf_token %} {{form.media}} {{form.as_p}} <button class="btn btn-info">Publish</button> </form> </div> {% endif %} my staff user can post,edit,publish blog from django admin panel but how to enable those permission in html template. -
requests python in Django ASGI server
I am using Django ASGI server and am sending a post request but its not responding. Continuously displaying "sending request" in postman My views.py @csrf_exempt def test(Request): if Request.method == "POST": requests.post('http://localhost:8000/api/token/') return HttpResponse(response) My urls.py urlpatterns = [ path('', include('chat.urls')), path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls')), path('api/token/', jwt_views.TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh'), ] This request is fine This request is not working -
WebDriver Execution Denied permission error on Cpanel
Hello I am using Chrome web driver for automation process. This Script Extract data from different websites. Everything is working fine on my local host but On deployment it Throwing permission error in execution. i have change the Permissions but still getting the same error... Can anyone help me in this options = webdriver.ChromeOptions() options.add_argument("headless") driver = webdriver.Chrome(executable_path="payviacoins.xtradehub.com",chrome_options=options) ERROR Message: 'chromedriver' executable may have wrong permissions. Please see https://sites.google.com/a/chromium.org/chromedriver/home -
Saving cookies via Python HTTP class
I have an extrenal authentication web application which isn't a part of my base web app. I would like to save auth token after succesfully login process into my main app. The only one available method is using BE for that. We have a PY/Django on BE. I was considering to use HTTP class with .set_cookie method to do that, but Im afraid about secure aspect of that process. Is using BE to save a cookies by HTTP class is safe? Is there any chance to malform/compromise that process from outside? -
Django Rest Framework: Multiple branches of API w/ varying queryset/permissions
In my Django-Rest-Framework application, I have the need to divide the API into two branches such as: /api/public/... /api/private/... Consider a model Analysis like so: from django.db import models from django.conf import settings class Analysis(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) public = models.BooleanField(default=True) What I want then is: /api/public/analysis => filter queryset with Q(public=True) /api/private/analysis => filter queryset with Q(user=request.user) | Q(public=False) Similar pattern is required in 5+ models. I have thought of 2 half-baked solutions: 1. AbstractViewSet sub-classed into PublicViewSet and PrivateViewSet class AbstractAnalysisViewSet(viewsets.ReadOnlyModelViewSet): queryset = Analysis.objects.all() serializer_class = AnalysisSerializer ordering = [ "-created_at", ] permission_classes = [IsAuthenticated,] class PrivateAnalysisViewSet(AbstractAnalysisViewSet): def get_permissions(self): permissions = super(PrivateAnalysisViewSet, self).get_permissions() if self.action in ["retrieve"]: permissions.append(HasObjectPermission()) return permissions def get_queryset(self): queryset = super(PrivateAnalysisViewSet, self).get_queryset() if self.action in ["list"]: auth_user = self.request.user query = Q(user=auth_user) | Q(public=False) queryset = queryset.filter(query) return queryset class PublicAnalysisViewSet(AbstractAnalysisViewSet): def get_permissions(self): permissions = super(PublicAnalysisViewSet, self).get_permissions() if self.action in ["retrieve"]: permissions.append(IsPublicObjectPermission()) return permissions def get_queryset(self): queryset = super(PublicAnalysisViewSet, self).get_queryset() if self.action in ["list"]: query = Q(public=True) queryset = queryset.filter(query) return queryset This would work but I don't really want to duplicate views into multiple classes like that because then I also need to register multiple viewsets with the DRF router. As I … -
Store HTML field data after refresh
I am building a BlogApp and I am trying to implement city model field in template. I am accessing and saving using field in template input method using :- <input data-city-picker="true" name='city'>. BUT When i write city and save it then it is successfully saving in DataBase BUT when i refresh the page then city name automatically disappear from the field BUT when i check on admin section then city is showing successfully BUT choosen city name in not in the text area anymore. views.py def edit_location(request): if request.method == 'POST': location_form = EditLocation(request.POST, request.FILES, instance=request.user.profile) if location_form.is_valid(): custom_form = location_form.save(False) custom_form.save() messages.success(request,"Location Saved") return redirect('profile') else: location_form = EditLocation(instance=request.user.profile) context = {'location_form':location_form} return render(request, 'edit_city.html', context) edit_city.html <div class="container"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <table> <input data-city-picker="true" name='city'> </textarea> </table> <button type="submit">Save Changes</button> </form> </div> I know i can also access the model's city field using {{ location_form.city }} BUT using this way i will not be able to access city's choice library. AND the city is successfully showing when i access city name BUT whenever i try to edit city name then city name is not in the textarea. I have no idea, What am i doing … -
How I can get the pk in the home view www.mywebsite.com
I tried to get the pk from this function def home_view(request, pk): but because this in home view www.site.com it return error home_view() missing 1 required positional argument: 'pk' so it is didn't worked with me My qustion is how I can pass pk to the template that in website domain without any extra urls like this www.site.com My view def home_screen_view(request, pk, *args, **kwargs): post= Post.objects.filter(pk=pk) #here I want to get the pk comment = PostCommentIDF.objects.filter(post=post) return render(request, 'personal/home.html', {'comment': comment) -
Django - automate CRUD from models (DRY approach)?
I am new to Django but not to developing. I need to make an application in which user can do CRUD operations (Create, Read, Update, Delete). This functionality should apply to all models and the fields for Create & Update will be auto-generated from model attributes. What I describe is pretty much the functionality that comes with the Admin page. However, I want to use it in my own app instead of using the Admin app. For example, let's suppose we have Author and Book models: (models.py) from django.db import models class Author(models.Model): first_name = models.CharField(max_length=60) last_name = models.CharField(max_length=60) def __str__(self): return self.last_name class Book(models.Model): title = models.CharField(max_length=60) author = models.ForeignKey(Author, on_delete=models.CASCADE) def __str__(self): return self.title I suppose that the above information (models) could be enough for CRUD operations, without repeating code of the same logic for each model. I am aiming at a functionality like in admin page where all you have to do is register your model. I am aware of ModelForm and Generic Views but while they help avoiding hard-coding form fields, I have not found a non-repetitive coding approach. I would like to avoid approaches like the following where same code is being duplicated for each … -
Django - PDF file not uploading but path is available
I'm trying to upload a pdf file to the database with forms but however the file isn't send to the server. models.py class Presse(models.Model): pdf = models.FileField() forms.py class PresseForm(forms.ModelForm): class Meta: model = Presse fields = '__all__' I tried same way I do when uploading images, which works fine. Somewhere I have an error or forgot something I didn't know about. views.py def presse(request): article = Presse.objects.get(id=1) if request.method == 'POST': form = PresseForm(request.POST, request.FILES, instance=article) if form.is_valid(): form.save redirect('main:presse') else: form = PresseForm(instance=article) return render(request, 'main/presse.html', { 'article': article, 'form': form }) presse.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button class="btn btn-success">Ersetzen & speichern</button> </form> If I upload a file after getting redirected I get error 404 GET http://localhost:8000/media/Untitled.pdf 404 (Not Found) The path is correct but the file wasn't served. Do you have an idea where the problem is? -
Django SECRET_KEY SyntaxError: invalid syntax
Just started to learn Django and ran into an error. When starting migrations! I watched a video on YouTube. and fulfilled all the conditions as in the video. But I got an error https://b.radikal.ru/b20/2105/d8/428b3c29860e.png (venv) D:\django-sites\testsite\mysite>python manage.py makemigrations Traceback (most recent call last): File "D:\django-sites\testsite\mysite\manage.py", line 22, in <module> main() File "D:\django-sites\testsite\mysite\manage.py", line 18, in main execute_from_command_line(sys.argv) File "D:\django-sites\testsite\venv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_comma nd_line utility.execute() File "D:\django-sites\testsite\venv\lib\site-packages\django\core\management\__init__.py", line 363, in execute settings.INSTALLED_APPS File "D:\django-sites\testsite\venv\lib\site-packages\django\conf\__init__.py", line 82, in __getattr__ self._setup(name) File "D:\django-sites\testsite\venv\lib\site-packages\django\conf\__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "D:\django-sites\testsite\venv\lib\site-packages\django\conf\__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\Skyba Vyacheslav\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_mod ule return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 786, in exec_module File "<frozen importlib._bootstrap_external>", line 923, in get_code File "<frozen importlib._bootstrap_external>", line 853, in source_to_code File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "D:\django-sites\testsite\mysite\mysite\settings.py", line 22 SECRET_KEY = 'django-insecure-v6o#d_au9g#5%3*s(-_vh7mq=!65v7446&m3q)+@zn2yd4806g' ^ SyntaxError: invalid syntax enter image description here """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 3.2.2. For more information on this file, see … -
Python List data to Django ORM query
Let say, I have a list data for example: data = [ {'id': 1, 'name': 'brad', 'color': 'red', 'tags': [], 'author': {'name': 'admin'}}, {'id': 2, 'name': 'sylvia', 'color': 'blue', 'tags': [], 'author': {'name': 'user'}}, {'id': 3, 'name': 'sylwia', 'color': 'green', 'tags': [], 'author': {'name': 'admin'}}, {'id': 4, 'name': 'shane', 'color': 'red', 'tags': [], 'author': {'name': 'admin'}}, {'id': 5, 'name': 'shane', 'color': 'red', 'tags': ['python', 'django'], 'author': {'name': 'user'}} ] and I want to make it ORM'able, such as what Django has doing: ModelName.objects.filter(color__icontains="gree") And this what I have do; import operator from collections import namedtuple from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist class DataQuerySet: """ Custom ORM for List dict data, https://stackoverflow.com/a/58351973/6396981 """ allowed_operations = { 'gt': operator.gt, 'lt': operator.lt, 'eq': operator.eq, 'icontains': operator.contains } def __init__(self, data): self.data = data def all(self): return self.data def filter(self, **kwargs): """ >>> kwargs = {'name': 'sylwia', 'id__gt': 1} >>> DataQuerySet().filter(**kwargs) [{'id': 3, 'name': 'sylwia', 'color': 'green'}] """ operation = namedtuple('Q', 'op key value') def parse_filter(item): """item is expected to be a tuple with exactly two elements >>> parse_filter(('id__gt', 2)) Q(op=<built-in function gt>, key='id', value=2) >>> parse_filter(('id__ ', 2)) Q(op=<built-in function eq>, key='id', value=2) >>> parse_filter(('color__bad', 'red')) Traceback (most recent call last): ... AssertionError: 'bad' … -
How to create a query across a M2M Relation with conditional aggregation in Django3?
I came up with this simple data model for a small quiz night. Now I want to create a queryset which contains the earned points (count if answer.is_correct is true) for each team and turn. Furthermore I want to show the earned points for each team in total. Unfortunately I dont get the annotate and values logic for Many2Many relations. class Team(models.Model): name = models.CharField(max_length=100) class Game(models.Model): attending_team = models.ManyToManyField(Team, blank=True) title = models.CharField(max_length=200) class Turn(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE) title = models.CharField(max_length=200) class Question(models.Model): turn = models.ForeignKey(Turn, on_delete=models.CASCADE) question_text = models.CharField(max_length=500) class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) team = models.ForeignKey(Team, on_delete=models.CASCADE) is_correct = models.BooleanField(default=False) answer_text = models.CharField(max_length=500, blank=True, null=True) The leaderboard should look like the following table: Rank Team name Turn 1 Turn 2 Turn 3 Total 1 Team A 3 2 5 10 2 Team B 1 1 3 5 3 Team C 1 3 0 4 So I tried the following query in my view to display the total earned points per team: def leaderboard(request, game_id): game = Game.objects.get(id=game_id) turns = Turn.objects.filter(game=game) teams_turns = Team.objects.filter(game=game_id, answer__is_correct=True).annotate(num_correct_answers=Count('answer__id')) # example for total earned points of first team print(teams_turns[0].name, teams_turns[0].num_correct_answers) This works but I think it is not the best … -
Django Rest Framework - Could not resolve URL for hyperlinked relationship using view name "product-detail"
I'm struggling with DRF. When I try to obtain a list of products using: requests.get("http://127.0.0.1:8000/products/").json() Server error 500 occurs and an error is displayed as in the title: Could not resolve URL for hyperlinked relationship using view name "product-detail" However, when I try obtain a single product, request is successful: requests.get("http://127.0.0.1:8000/products/t/").json() {'id': 1, 'url': 'http://127.0.0.1:8000/products/t/', 'name': 't', 'slug': 't', 'description': '', 'order': 'http://127.0.0.1:8000/orders/1/', 'ingredients': '', 'allergens': '', 'suggested_products': [], 'image': None, 'available': True, 'price': 100.0, 'category': 'http://127.0.0.1:8000/categories/t/'} So what's the problem here? I'm not using app namespacing, so this is not the cause. Serializer code: class ProductSerializer(serializers.HyperlinkedModelSerializer): # TODO: Fix URL url = serializers.HyperlinkedIdentityField("product-detail", lookup_field="slug", read_only=True) category = serializers.HyperlinkedRelatedField("category-detail", queryset=Category.objects.all(), lookup_field="slug") image = Base64ImageField(max_length=settings.MAX_UPLOAD_SIZE, required=False) class Meta: model = Product fields = ("id", "url", "name", "slug", "description", "order", "ingredients", "allergens", "suggested_products", "image", "available", "price", "category") View code: class ProductList(generics.ListCreateAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer lookup_field = "slug" @method_decorator(cache_page(LONG_CACHING_TIME)) @method_decorator(vary_on_headers("Accept-Language")) def dispatch(self, *args, **kwargs): return super(ProductList, self).dispatch(*args, **kwargs) class ProductDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer lookup_field = "slug" Urlconf: path("products/", ProductList.as_view(), name="product-list"), path("products/<slug:slug>/", ProductDetail.as_view(), name="product-detail") Thank you. -
l have trying to send mail through django, but it got failed. I am not getting any error. But the page redirecting to the same page with different URL
While I am sending mail through django, I am not getting any error. But the page redirecting to the same page with different URL in web page and that URL is reflecting in console also. Finally the issue is "mail not sending" Here is the code in settings.py EMAIL_HOST='smtp.gmail.com' EMAIL_PORT=587 EMAIL_HOST_USER='fhjfhfjs@gmail.com' EMAIL_HOST_PASSWORD='fjsfghsfjk@123' EMAIL_USE_TLS= True Here is the code in views.py from django.core.mail import send_mail from blog.forms import Email_Form def mail_view(request,id): post=get_object_or_404(Post,id=id,status='published') sent=False if request.method=='GET': form=Email_Form() else: form=Email_Form(request.POST) if form.is_valid(): cd=form.cleaned_data() send_mail('sub','message','jfsdhfsdjk@gmail.com',[cd['to']]) sent=True return render(request,'blog/sharebymail.html',{'post':post,'form':form,'sent':sent}) Here is the code in html file {%if sent%} <h1>Post Sent Successfully</h1> <h2>Post with title {{post.title}} information shared by email</h2> {%else%} <h1>Share Post "{{post.title}}" By Mail</h1> <form> {{form.as_p}} {%csrf_token%} <input type="submit" class="btn btn-primary btn-lg", value="Send Mail"> </form> {%endif%} Here is the url in which the page redirecting http://127.0.0.1:8000/4/share/?name=djfkj&email=fhsdjf%40gmail.com&to=fjshnf%40gmail.com&comments=kgjlfsgjfs&csrfmiddlewaretoken=RBXpbZW74LqvdRXdQLufO75rHmmXVMN8y9i1dN3Go9bBlpZTyEgtYEn2YGR3ZQDy -
The best way to connect Next.js CSR React app, Django and PostgreSQL
My question concerns programming a full-stack app. On the frontend, I have a Next.js React app. I want to render it on the client-side and probably use SWR. On the backend, I have a Django app with a PostgreSQL database. I have seen two approaches to make all of these work together. The first one is to use Django to serve Next.js React app with django-webpack-loader and then to load React app within Django template. The second one is to build two separate apps - frontend (Next.js) and backend (Django + PostgreSQL) and deploying them on two servers (e.g. Docker container). I have read this article and it makes me lean towards the second option. However, it is a pretty old solution and maybe some things have changed since then. What is the most optimal solution when it comes to connecting Next.js React Client-side rendered, Django and PostgreSQL? -
How to pass a Jinja variable inside a Svelte component (Django/Flask)
I have a Flask app, and I need to pass a variable called var to Svelte component App.Svelte In a HTML, I would do {{ var }} but this confuses Svelte as it uses { } for its delimiters, and says var is not defined. In Vue, we can define different delimiters for Jinja (such as []) to solve this problem, but in Svelte I could not find how to do it. How can I pass a variable to Svelte? -
Django how to change value in models field on button click
I've made a Django app which is like a trouble ticket. When a user click a specific button the ticket should automatically get closed i.e., a boolean field. I've been trying to save the value on button click but I'm getting an integrity error. Models.py class Risk(models.Model): id = models.CharField(primary_key=True, editable=False, max_length=10) time = models.DateTimeField(default=timezone.now, blank=True) header = models.CharField(max_length=15, null=True) start_date = models.DateField(null=True, blank=True) ...... close = models.BooleanField(default=False) Views.py class PostUpdateView(LoginRequiredMixin, UpdateView): def form_valid(self, form): form.instance.author = self.request.user risk_id=self.kwargs['pk'] elif 'btn-close1' in self.request.POST: profil=get_object_or_404(Risk, pk=risk_id) profil.close=True profil.save(update_fields=["close"]) return super().form_valid(form) Error: IntegrityError at /RISK00069/update/ UNIQUE constraint failed: blog_risk.id Request Method: POST Request URL: http://127.0.0.1:8000/RISK00069/update/ Django Version: 3.2 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: blog_risk.id Exception Location: C:\Users\acchaka\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\base.py, line 423, in execute Python Executable: C:\Users\acchaka\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.1 Also, I would like to update "start_date" field on button click with todays date + 24 days, Please guide me on how to do that. -
How will I trigger a function on losing focus from TextInput in python Django?
I am following CS50W and have a project wiki in Django Python. I want to call a function from views.py to run when TextInput lose focus. and will try to validate that text from the topic list. function to be called from views.py def myCheckFunction(request, entry): page = util.get_entry(entry) if page is None: return HttpResponse('Title not found') else: return HttpResponse('Title exists') Entry in urls.py path("myCheckFunction", views.myCheckFunction, name="check"), NewPage.html <body> <form method="post"> {{ form }} </form> </body> createNewPage.html <form> {% csrf_token %} <div class="form-group" style="margin-right: 20%"> <label for="InputCaption"><b>New Page Title</b></label> {% include 'encyclopedia/newPage.html' %} <br> <label for="NewPageText"><b>Enter Page Text</b></label> <textarea class="form-control" id="NewTopicText" name="NewPageText" rows="14"></textarea> </div> <div class="btn-save-placement flex-container" style="height: 48px; padding-top: 0px;"> <button class="btn btn-outline-dark" type="submit">Save New Page</button> </div> </form> forms.py class CreateNewList(forms.Form): name = forms.CharField(label="", widget=forms.TextInput( attrs={ 'autofocus': 'autofocus', 'onfocusout': '/myCheckFunction/', 'class': 'form-control', 'placeholder': 'Type Topic Title Here...', })) -
Cannot validate input through == equals in Python
Im creating a Django web and able to let user select which parameter to parse the email ingestion function. When user click on "OK", the email ingest function will take the input parameter and validate through the if else statement . User can validate through Subject or text of an email and then it can parse with three conditions: equals, contain and does not contain. The subject part is all fine but when come to the text part, the equals is not functioning. It always return me no email even I entered the correct input to match. The main function of this program is able to send an email to a particular user when the condition is triggered. Views.py from django.shortcuts import render from django.http import HttpResponse import datetime import email import imaplib import mailbox import smtplib def index(request): return render(request,'DemoApp/hi.html') def send(request): EMAIL_ACCOUNT = "xxx@gmail.com" PASSWORD = "xxx" mail = imaplib.IMAP4_SSL('imap.gmail.com') mail.login(EMAIL_ACCOUNT, PASSWORD) mail.list() mail.select('inbox') result, data = mail.uid('search', None, "UNSEEN") # (ALL/UNSEEN) i = len(data[0].split()) for x in range(i): latest_email_uid = data[0].split()[x] result, email_data = mail.uid('fetch', latest_email_uid, '(RFC822)') # result, email_data = conn.store(num,'-FLAGS','\\Seen') # this might work to set flag to seen, if it doesn't already raw_email = …