Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Rendering local web pages as an iFrame in Django
I have a view that uploads a zip file, checks if it contains an index.html file, and unzips it in a specific folder in the static directory. I want to be able to view this by going to a page where there is an iFrame pointing to this directory, and the user will be able to navigate inside this html page. But I can't seem to get it to work. Here is the function that uploads the zip file, and the view that uses it: views.py: @user_passes_test(lambda u: u.is_staff or u.is_superuser) def createCategory(request): if request.method == "POST": name = request.POST.get("name_kw") lang = request.POST.get("lang_kw") moduleid = request.POST.get("module_kw") zip = request.FILES.get("zip_kw") category = Category() category.name = name category.lang = lang category.module = Module.objects.get(id=moduleid) category.zip = zip category.created_by = request.user try: if zip.name.endswith(".zip"): rtn = publish_doc(category.name, zip) if rtn == "No index file found": messages.error( request, "Pas de fichier index.html détecté. Assuez-vous qu'un fichier index.html est présent dans votre fichier ZIP", ) return redirect("categoryList") else: category.root = rtn category.save() messages.success(request, "Catégorie créée avec succès") print("categorie et zip créées") return redirect("categoryList") else: messages.error( request, "Seuls les fichiers .ZIP sont acceptés", ) return redirect("categoryList") except IntegrityError: print("erreuuuuuuuur") messages.error( request, "Une erreur s'est produite. Veuillez réessayer … -
Using templatetag "get_comment_list" from view, in Django comments?
I have a template expression {% get_comment_list for data.post as comment_list %}, it uses get_comment_list from Django-comments. It gets a list of comment objects for a specified object (in this case the Post object through data.post) However, I'm currently working on client side Ajax API to retrieve the comments and its related user data. So I cannot use the template html way to get/render the data, but in a view, Python script. I found that the tag get_comment_list is defined as follows: # django_comments/templatetags/comments.py @register.tag def get_comment_list(parser, token): return CommentListNode.handle_token(parser, token) I know how to import custom template tag to a view so Python can use it, like: @register.simple_tag def addFoo(value=""): return value + "Foo." The above type of tag is simply passing a string value, but the get_comment_list(parser, token) tag requires two parser thing and object thing object, it's not a plain string type. Now, I have no idea how I can construct that parser and token or pass a model to get_comment_list to get the comment objects. Is it possible to use this type of template tag in a view? Thanks. -
Connection to the postgres refused in Github Actions
I have a Django app with Postgres default database, running in docker. I also use Github actions as a CI. When I run the tests locally using the command docker-compose run --rm app sh -c "python manage.py wait_for_db && pytest -s -v" everything works fine. However, I get the following error when I use the same command in GitHub actions: E django.db.utils.OperationalError: connection to server at "postgres" (172.18.0.2), port 5432 failed: Connection refused E Is the server running on that host and accepting TCP/IP connections? /usr/local/lib/python3.10/site-packages/psycopg2/__init__.py:122: OperationalError Here is my github workflow code: # This workflow will install Python dependencies, run tests and lint with a single version of Python # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions name: Python application on: push: branches: [ main ] pull_request: branches: [ main ] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up Python 3.10 uses: actions/setup-python@v2 with: python-version: "3.10" - name: Install docker-compose run: | pip install docker-compose - name: Test with pytest run: | docker-compose run --rm app sh -c "python manage.py wait_for_db && pytest -s -v" My docker-compose code: version: "3" services: postgres: image: postgres:14-alpine environment: - POSTGRES_DB=app - POSTGRES_USER=postgres - POSTGRES_PASSWORD=123 ports: - "5432:5432" app: build: context: … -
Django REST Framework update record mixin
I'm using Django 3.2 and the last version of djangorestframework. I need to be able to update the values of JobStatus record already crated before. As example I have { "id": 1, "status_timestamp": "2022-04-07T10:51:42Z", "status_activity": "Sync DDT", "status_status": "running", "launcher": 1 } and I need to obtain this (in the DB) via API { "id": 1, "status_timestamp": "2022-04-07T11:51:42Z", "status_activity": "Sync DDT", "status_status": "completed", "launcher": 1 } Can someone help me out? PS I need to mantain the Token authentication method MODELS class JobStatus(models.Model): status_timestamp = models.DateTimeField() status_activity = models.CharField(max_length=200) status_status = models.CharField(max_length=200) launcher = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.RESTRICT) class Meta: verbose_name = "Status" verbose_name_plural = "Status list" def __str__(self): return str(self.status_timestamp) + " " + self.status_activity URLS from django.urls import path, include from apps.api_c import views from rest_framework.routers import DefaultRouter from rest_framework.urlpatterns import format_suffix_patterns router = DefaultRouter() router.register('alert', views.AlertViewSet) router.register('jstatus', views.UpdateStatus) urlpatterns = [ ... path("", include(router.urls)), ] VIEWS class UpdateStatus(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin): """update status""" authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) serializer_class = StatusSerializer #queryset = JobStatus.objects.all() #TEST1 def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) #TEST2 def perform_update(self, serializer): serializer_class.update() -
Class-Based View of 'User' model auto-authenticates user
I've made a class-based view (DetailView) of app user's profile and for some reason anyone who visits the view is automatically considered authenticated even without entering any credentials. This happens without adding any extra logic in neither view nor template, just basic DetailView. The code is below: views.py from django.views.generic import DetailView from django.contrib.auth.models import User class ProfileDetail(DetailView): model = User template_name = 'index.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context urls.py from django.urls import path from .views import ProfileDetail urlpatterns = [ path('<int:pk>/', ProfileDetail.as_view()) ] template (index.html) {{ user.is_authenticated }} {# returns True #} {{ user }} {# returns the user with the corresponding id #} The question is why does Django do it and is there any way to circumvent it except of using function-based view? I've looked through the docs, but couldn't find an answer. -
Negative value will rise validation error
I want to implement custom validation for negative value , can any one help me for this. So in the object we do not allow user to add negative value. -
I am trying to get the weather details from an API on django however I am facing an error and I can't get past it
def index(request): if request.method == 'POST': start_city = request.POST['city'] city= str(urlparse(start_city)) start_url = 'https://api.openweathermap.org/data/2.5/weather?city='+city+'&appid=<APPID>' url = start_url.replace(' ','') res = urllib.request.urlopen(url).read() json_data = json.loads(res) context = { 'city': city, 'country': json_data['sys']['country'], 'windspeed':json_data['wind']['speed'], 'temperature':json_data['main']['temp'], } else: city='' return render(request,'index.html', {'city':city}) ERROR HTTPError at / HTTP Error 400: Bad Request Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 4.0.3 Exception Type: HTTPError Exception Value: HTTP Error 400: Bad Request -
Why LoginRequiredMixin don't stop my dispatch flow, when user is not authenticated
I have no clue why in this View, dispatch does not end after super(): class CreateBookView(LoginRequiredMixin, CreateView): template_name = 'library/create_book.html' form_class = BookForm def dispatch(self, request, *args, **kwargs): result = super().dispatch(request, *args, **kwargs) if self.request.user.is_authenticated and not self.request.user.contactform.is_completed: return redirect(reverse_lazy('edit_contacts') + f"?next={self.request.path}#edit") return result def form_valid(self, form): form.instance.owner = self.request.user form.instance.category = self._set_category(form) return super().form_valid(form) def get_success_url(self): pk = self.request.user.pk default_redirect = reverse_lazy('show_books_dashboard', kwargs={'pk': pk}) next_page = self.request.GET.get('next') return next_page if next_page else default_redirect @staticmethod def _set_category(form): category = form.cleaned_data.get('category') category_name = form.cleaned_data.get('category_name') if category or not category_name: return category new_category, created = Category.objects.get_or_create(name=category_name) return new_category But in this it works as I expected and end it: class DetailsNotificationView(LoginRequiredMixin, AuthorizationRequiredMixin, DetailView): model = Notification context_object_name = 'notification' template_name = 'common/notifications/notifications_details.html' authorizing_fields = ['recipient'] def dispatch(self, request, *args, **kwargs): result = super().dispatch(request, *args, **kwargs) notification = self.get_object() notification.is_read = True notification.save() if notification.offer: return redirect('show_offer_details', pk=notification.offer.pk) return result I expect LoginRequiredMixin to handle error immediately after super() when the user is not authenticated and stop dispatch flow. I cannot figure out why it does not work as expected in CreateBookView. Any ideas ? -
mod_wsgi not using venv
Hello I am trying to setup a Django project using Apache with mod_wsgi. I have set wsgi like this WSGIDaemonProcess Breath python-home=/var/www/vhosts/Breath/env/ WSGIProcessGroup Breath WSGIScriptAlias / /var/www/vhosts/Breath/BreathAlessio/wsgi.py process-group=Breath So I'd like to launch the wsgi.py with the version in the venv, but by checking the version I see it runs it with the default python installation. What am I doing wrong? I have tried to set all the permission to 777 and to change the owner of the project but nothing changed Thanks in advance. -
Pip: Fatal error in launcher: Unable to create process using
I developed a complete Django project on my system. When I try to run on another system, after activating my virtual environment "data". It shows me the path of my system (where it's developed). (data) PS D:\Hafiz\Data_Collection> pip Fatal error in launcher: Unable to create process using '"D:\Masters_FIT\4th\Webdatabese\Project\Data_Collection\Data\Scripts\python.exe" "D:\Hafiz\Data_Collection\data\Scripts\pip.exe" ': The system cannot find the file specified. On other systems python, pip, and Django are installed with their latest versions and paths are also added. I tried a new project there and it's working properly. -
How set username to ForeignKey
I want to set value, but i don't know how do it. Error: RelatedObjectDoesNotExist at /comments/ commentsTabl has no avtor. Request Method: GET Request URL: http://localhost:8000/comments/ Django Version: 4.0.2 Exception Type: RelatedObjectDoesNotExist Exception Value: commentsTabl has no avtor. Exception Location: D:\python39\lib\site-packages\django\db\models\fields\related_descriptors.py, line 197, in get Python Executable: D:\python39\python.exe Python Version: 3.9.6 Python Path: ['D:\Django\ForumXT\first', 'D:\python39\python39.zip', 'D:\python39\DLLs', 'D:\python39\lib', 'D:\python39', 'D:\python39\lib\site-packages'] Server time: Thu, 07 Apr 2022 12:20:35 +0000 models.py class commentsTabl(models.Model): Text = models.TextField(verbose_name='Text') date = models.DateTimeField(default=timezone.now, verbose_name='date') avtor = models.ForeignKey(User, verbose_name='avtor', on_delete=models.CASCADE, to_field="username") def __str__(self): return f'Comment {self.avtor} at {self.date}' class Meta: verbose_name = "Comment" verbose_name_plural = "Comments" views.py def comments(request): data = { 'com': reversed(commentsTabl.objects.all()) } if request.method =="POST": form = commentsTabl(request.POST) if form.is_valid(): form.save() else: form = commentsTabl() return render(request, 'home/comments.html', data, {'form':form}) -
Django csrf token + react
I'm using django for my API and react for my frontend app. My problem is I do not know how to get csrf token which is needed to submit the login form (I do not need registrition form, just few users). This is the code for handling the /accounts/login : from django.contrib.auth import authenticate, login from django.http import JsonResponse from json import loads def login_user(request): body_unicode = request.body.decode('utf-8') body = loads(body_unicode) username = body['username'] pwd = body['pwd'] user = authenticate(request, username=username, password=pwd) try: if user.is_authenticated: login(request, user) email = User.objects.get(username=username).email return JsonResponse({"username":username, \ "pwd":pwd, \ "email":email }, \ status=200)` except Exception as expt: return JsonResponse({"error": str(expt)}, status=401) And in my react app I'm trying to make a request for logging /accounts/login using the X-CSRFToken header and the csrf token goten by the getCookie() function (found here), but it is always null and the response always rejected with 403 status code. Could you please show me how I can handle that situation please ? (I do not want to use csrf_exempt which pose security issues). -
I can't filter the product vendor for orders
I want special users (vendors) to see their own orders in their django admin. When ever I tried that it filters out the user that ordered the products. Here are the codes. I connected the vendors in my product model. I can't figure out how to connect vendors with their respective orders. class Order(models.Model): STATUS = ( ('New', 'New'), ('Accepted', 'Accepted'), ('Preparing', 'Preparing'), ('OnShipping', 'OnShipping'), ('Completed', 'Completed'), ('Canceled', 'Canceled'), ) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) code = models.CharField(max_length=5, editable=False) first_name = models.CharField(max_length=10) last_name = models.CharField(max_length=10) phone = models.CharField(blank=True, max_length=20) address = models.CharField(blank=True, max_length=150) city = models.CharField(blank=True, max_length=20) country = models.CharField(blank=True, max_length=20) total = models.FloatField() status=models.CharField(max_length=10,choices=STATUS,default='New') ip = models.CharField(blank=True, max_length=20) adminnote = models.CharField(blank=True, max_length=100) create_at=models.DateTimeField(auto_now_add=True) update_at=models.DateTimeField(auto_now=True) class OrderProduct(models.Model): STATUS = ( ('New', 'New'), ('Accepted', 'Accepted'), ('Canceled', 'Canceled'), ) order = models.ForeignKey(Order, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) variant = models.ForeignKey(Variants, on_delete=models.SET_NULL,blank=True, null=True) # relation with variant quantity = models.IntegerField() price = models.FloatField() amount = models.FloatField() status = models.CharField(max_length=10, choices=STATUS, default='New') create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.product.title class OrderAdmin(admin.ModelAdmin): list_display = ['first_name', 'last_name','phone','city','total','status','create_at'] list_filter = ['status'] readonly_fields = ('user','address','city','country','phone','first_name','ip', 'last_name','phone','city','total') can_delete = False inlines = [OrderProductline] class OrderProductAdmin(admin.ModelAdmin): list_display = ['user', 'product','price','quantity','amount'] list_filter = ['product'] … -
typeError: unsupported operand type(s) for -: 'long' and 'datetime.date'
For this piece of code (the model had other things too, but I deleted them so I can get a minimal example): class Invoice(models.Model): """ Represents one invoice line in the imported data. """ payment_date = models.DateField( blank=True, null=True, help_text="Format: YYYY-MM-DD") date = models.DateField(db_index=True, blank=True, null=True, help_text="Format: YYYY-MM-DD") date_diff = models.IntegerField(default=0) class Meta: app_label = 'analysis' ordering = ('claim_order',) def clean(self): self.date_diff = ( self.payment_date - self.date).days if (self.payment_date and self.date) else 0 I get typeError: unsupported operand type(s) for -: 'long' and 'datetime.date' and I can't see why, because both of the fields are DateFields. Can anybody help me understand why this happens? Thanks. -
Django - Replication lag
Prerequisites: class Task(models.Model): class TaskStatus(models.TextChoices): HIDDEN = 'hidden', _('hidden') NEW = 'new', _('new') IN_PROGRESS = 'in_progress', _('in progress') DONE = 'done', _('done') FAILED = 'failed', _('failed') PLANNED = 'planned', _('planned') REVOKED = 'revoked', _('revoked') title = models.CharField(max_length=500) performer = models.ForeignKey(User, on_delete=models.CASCADE) status = models.CharField(choices=TaskStatus.choices, default=TaskStatus.HIDDEN, max_length=25) class TaskTransition(models.Model): task = models.ForeignKey('tasks.Task', on_delete=models.CASCADE, related_name='transitions') actor = models.ForeignKey(User, on_delete=models.RESTRICT, related_name='transitions') old_status = models.CharField(choices=TaskStatus.choices, max_length=25) new_status = models.CharField(choices=TaskStatus.choices, max_length=25) class TaskView(ModelViewSet): queryset = Task.objects.all() serializer = TaskSerializer class CreateTaskTransitionView(mixins.RetrieveModelMixin, generics.CreateAPIView): serializer_class = CreateTaskTransitionSerializer class CreateTaskTransitionSerializer(serializers.ModelSerializer): task = serializers.HiddenField(default=HiddenTaskField()) actor = serializers.HiddenField(default=serializers.CurrentUserDefault()) class Meta: model = TaskTransition fields = '__all__' def validate(self, attrs): # allowed status transitions: # hidden > new # new > in_progress, failed # in_progress > done, failed return attrs def save(self, **kwargs): task = self.validated_data['task'] new_status = self.validated_data['new_status'] TaskTransition.objects.create( task=task, new_status=new_status, old_status=task.status, actor=self.validated_data['actor'] ) task.status = new_status task.save() return {} We use two databases. First default for writing and replica for reading. Because of validation as you can see only one unique task transition can be done. But sometimes it happens that there can be multiple same transitions. For example 5 transitions in_progress > done. And when retrieve task instance task is with not actual status. It's obvious that this … -
what on_delete option to use in django app?
I have an Article model that allows admins to publish articles. Each article is assigned to a user that is creating this article. I want to make sure that all articles will stay untouched even if I delete the author of this particular article. I chose on_delete=models.DO_NOTHING to be sure that nothing except user account will be removed but I am not quite sure that is the most effective way. class Article(models.Model): id = models.AutoField(primary_key=True) author = models.ForeignKey(User, blank=True, null=True, on_delete=models.DO_NOTHING) title = models.CharField('Title', max_length=70, help_text='max 70 characters') body = models.TextField('Description') Question Should I use another option to use or DO_NOTHING is good enough. Obviously the most important to me is that author's name will be visible in the article after deletion and the article itself cannot be removed. -
Django admin prepopulated fields and fieldsets
I am using Django 3.2 I have the following model: class Foo(models.Model): title = models.CharField() slug = models.SlugField() # remaining fields listed below In Admin manager, I have the model: class FooAdmin(admin.ModelAdmin): fieldsets = [ ('General', { 'fields': [ 'title', 'description', 'information', 'cover_photo', 'gallery', ] }), ('Details', { 'fields' : [ 'is_cancelled', 'start', 'finish', 'video_url', ] }), ] prepopulated_fields = {'slug': ('title',), } admin.site.register(Foo, FooAdmin) When I attempt to create a new Foo in the admin manager, I get the error: KeyError: "Key 'slug' not found in 'FooForm'. Choices are: cover_photo, description, finish, gallery, information, is_cancelled, start, title, video_url." When I add the slug field to the list of fieldsets, it works, but then the slug field is shown on the form (which I don't want). I know that I can solve this by overriding Foo.save(), but I want the admin manager to handle this for me. So, how do I use fieldsets with prepopulated fields that are not supposed to appear on the form? -
pop up modal appears again when clicked on back button
i have created a confirmation pop up modal using javascript in django's html page, my html template is generating delete links using for loop, so my my logic is i have used target the clicked html element using window event and then i fetch the value of href, store it in varibale, and then apply that value to the yes button of pop modal, and also set the href value of delete link to '#', so it should not work. now my problem is the modal is working properly, but aafter finishing the task, when clicked on browser back button, again the modal is appearing.enter image description here -
django.core.exceptions.ValidationError: ['“TRUE” value must be either True or False.']
I am trying to upload data in the django ORM by a script for which I have written this for index, row in df.iterrows(): allocated = row['is_allocated'] delivery_required_on = row['delivery_required_on'] linked = row['linked'] raised_by = row['raised_by'] raised_for = Company.objects.get(pk=row['raised_for']) ### double check rejected = row['is_rejected'] reason = row['reason'] remarks = row['remarks'] created = row['created_at'] owner = User.objects.get(pk=row['New owner']) j = literal_eval(row['flows']) flows = [] mobj = MaterialRequest.objects.create(owner=owner, is_allocated=allocated, delivery_required_on=delivery_required_on, linked=linked, raised_by=raised_by, raised_for=raised_for, is_rejected=rejected, reason=reason, remarks=remarks, created=created) It is running fine when the data is something like the following: But as soon as is_allocated reaches False it shows the following error: django.core.exceptions.ValidationError: ['“TRUE” value must be either True or False.'] I am unable to find something related to this -
python calculate rating by percent of complete
Let say, when student completed the course then he will get the percentage of his completion. Then we implement the max ratings is 5 stars which following these rules: 0%-4% => 0 star 5%-19% => 1 star 20%-39% => 2 stars 40%-59% => 3 stars 60%-79% => 4 stars 80%-100% => 5 stars So, based on student score: 0% percent complete will get 0 rating star. 10% percent complete will get 1 rating star. Also, another conditionals it can be 30% percent complete will get 2.5 rating stars. NOTE: The max 5 stars is dynamic value, it can be 10 stars. how we can accomplish this? -
Why is Heroku installing SQlite 3 even though I don't have it in requirements.txt
I am deploying a Django 3.2 website (with PG db backend) on Heroku, when I do a git push, this is a snippet of the console output: Enumerating objects: 18, done. Counting objects: 100% (18/18), done. Delta compression using up to 8 threads Compressing objects: 100% (11/11), done. Writing objects: 100% (11/11), 1.04 KiB | 265.00 KiB/s, done. Total 11 (delta 9), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Using buildpack: heroku/python remote: -----> Python app detected remote: -----> Using Python version specified in runtime.txt remote: ! Python has released a security update! Please consider upgrading to python-3.10.4 remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Requirements file has been changed, clearing cached dependencies remote: -----> Installing python-3.10.3 remote: -----> Installing pip 21.3.1, setuptools 57.5.0 and wheel 0.37.0 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip Why is Heroku installing SQlite3 - even though I don't have it in my requirements.txt? Heroku seems to install SQLite3 first, before checking what the requirements are - Why? -
Number of elements in database array using django
I am pretty new in django and I am trying to dispaly using django number of images that appears in my database on my datatable field called number of images Explanation : I have a document that contains several elements. One of these elements is an array called Feedback that contains an array called images with urls of photos. What I need is that I get number of all urls that appears in images array but not only in one but all the document in all Feedback array not only one array image. I have tried this line of code in my django template but it doesn't display the right number of images. Code: <td>{{ product.Feedback.2 | length }}</td> Here is a screenshot of my Mongodb database to clarify my expalanation : Any help would be great !Thank you. -
Reset password email from django doesn't appear in my mailbox
Scenario: In my django application, admin should create users using 'username' and 'email', 'password' will be generated auto .Welcome email will be sent to users with redirect link to reset password. Issue: after entering email for reset password the app should send email with link to confirm reset password. THE PROBLEM is the email it never show in user "inbox" but i can find it in app "outbox mails" How can i make it appear in user mailbox? Any Help or idea? I'm using: -Python3 -Django4 -enable two factor authentication(2FA) for Google account Settings.py: #SMTP Config EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = '587' EMAIL_USE_TLS = True EMAIL_HOST_USER = "webapp@app.com" DEFAULT_FROM_EMAIL = "MyApp <no-reply@app.com>" EMAIL_HOST_PASSWORD = "******" APP/URLS: urlpatterns = [ path('',views.login_user, name ='login'), #login fonction path path ('user_logout',views.user_logout, name = 'logout'), #logout function path path('dashboard/', views.dashboard, name='dashboard'),# dashoard view path path ('daily',views.DailyView, name = 'dailydashboard'),#daily view depath path ('monthly',views.MonthlyView, name = 'Monthlydashboard'),#monthly view path path ('yearly',views.YearlyView, name = 'Yearlydashboard'), #yearly view path path("reset_password/", auth_views.PasswordResetView.as_view(template_name="password/password_reset.html"), name="reset_password"), path('password_reset_done/', auth_views.PasswordResetDoneView.as_view(template_name="password/password_reset_done.html"), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="password/password_reset_confirm.html"), name='password_reset_confirm'), path('password_reset_complete/', auth_views.PasswordResetCompleteView.as_view(template_name='password/password_reset_complete.html'), name='password_reset_complete'), ] -
Foreign Key field cant not be save in Django
I have this two model that is related by a foreign key. I take response from a webhook regarding a transaction and save into the model. What i am trying to do is save the the foreign key element into the Transaction History but i keep getting error when data is about to be saved that Cannot assign "'1'": "TransactionHistory.level" must be a "Level" instance. model class Level(models.Model): name = models.CharField(max_length=200, null=True, blank=True,) fees_amount = models.PositiveSmallIntegerField() class TransactionHistory(models.Model): level = models.ForeignKey(Level, on_delete=models.CASCADE, null=True, blank=True, ) student_full_name = models.CharField(max_length=120) transaction_id = models.CharField(max_length=120) student_id_number = models.CharField(max_length=120) amount = models.DecimalField(default=0.0, max_digits=19, decimal_places=2) status = models.CharField(max_length=120, null=True, blank=True) email = models.EmailField(max_length=120, null=True, blank=True) phone = models.CharField(max_length=120, null=True, blank=True) date = models.DateTimeField(auto_now_add=True) View.py @csrf_exempt def webhook(request): # Verify if request came from Paystack if request.method == 'POST': response_data = json.loads(request.body) if response_data["event"] == "charge.success": transaction_id = (response_data["data"]["reference"]) if not TransactionHistory.objects.filter(transaction_id=transaction_id).exists(): status = (response_data["data"]["status"]) amountraw = (response_data["data"]["amount"]) student_full_name = (response_data["data"]["metadata"]["custom_fields"][0]["student_full_name"]) level = (response_data["data"]["metadata"]["custom_fields"][0]["level"]) student_id_number = (response_data["data"]["metadata"]["custom_fields"][0["student_id_number"]) email = (response_data["data"]["metadata"]["custom_fields"][0]["email"]) phone = (response_data["data"]["metadata"]["custom_fields"][0]["phone"]) amount = (str(int(amountraw) / 100)) if status == 'success': transaction = TransactionHistory( level=level, student_full_name=student_full_name, amount=amount, transaction_id=transaction_id, status=status, student_id_number=student_id_number, email=email, phone=phone, ) transaction.save() return HttpResponse(status=200) This is the error i get: raise ValueError( ValueError: Cannot … -
Django Taggit - insert hyperlink if the word in body matches with tag
I am using django-taggit to handle tags in my app. I am also using django-ckeditor in my body field. I'd like to implement a function or a decorator or anything that will look at the text in the body field, find automatically tags in the text, and insert hyperlink like this one: http://127.0.0.1:8000/tag/test1/. I am not sure where should I start and how to implement such a feature. I know that CKEditor offers such a feature and it can be found here but I believe that I need a premium version of CKEditor5, right? If it is free is there any other way to handle CKEditor configuration than React, Angular, and Vue? Can I use Boostrap to for setting up the link feature?