Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
save logs of database changes into database in django
I need to save log for changes of some tables into database so admin can read the logs and track users activities for example, I need to save logs of user table changes with these infos datetime chage happend, user who changed the user info (can be user him/her self or admin), fields that changed with their new values. this is my code the problem is, I don't know is this best practice?, is there any package for it, how can I access the user who made changes? and of course it is not just for user table. class CustomUser(AbstractUser): __pre_save_fields = {} def _get_field_value_dict(self): return {field.attname: getattr(self, field.attname, None) for field in self._meta.concrete_fields} def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__pre_save_fields.update(self._get_field_value_dict()) def save(self, **kwargs): in_memory_field_value_dict = self._get_field_value_dict() changed_fields_new_value_dict = dict( filter(lambda t: self.__pre_save_fields[t[0]] != t[1], in_memory_field_value_dict.items()) ) super().save(**kwargs) self.__pre_save_fields.update(self._get_field_value_dict()) if changed_fields_new_value_dict: UserChangeLog.objects.create(insert_edit_by_user_id=1, last_data=str(changed_fields_new_value_dict)) class UserChangeLog(models.Model): datetime_created = models.DateTimeField(auto_now_add=True) insert_edit_by_user = models.ForeignKey(AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL) last_data = models.TextField() -
centos7 django codes not showing
I wrote my codes. I took them to the server and along with that, I did the operations on this site (http://wiki.centos-webpanel.com/how-to-deploy-django-apps-using-apache-with-mod-wsgi-and-nginx). I am encountering this problem. How can i solve it. sites:www.diyetzone.com -
Django three-way pivot relationship?
im trying to make a setup that i'm unsure how to implement. Basically there are three tables: Cars(main data like name etc) Categories CarOptions (eg automatic. This table holds different option names) I want the user to be able that based on the category to have the option to select the options(user may select multiple categories). Hope what i wrote makes sense, so basically a "pivot" table is needed(or is there a better way?) with data: carId categoryId optionId Thank you -
What am I doing wrong in Django?
I'm following the Django tutorial on W3 Schools step by step, but am getting this at the views class. https://i.stack.imgur.com/xP0Ib.png -
How to call a python function from views.py in html template
I'm beginner with Django Framework and I need to finish a project. Right now I'm stuck on something. Please, someone help me. I'm redering a template "borrow.html". In html code I want to call a function from views.py. I tried like this: This is views.py: def borrowBook(request): return render(request,'app_system_borrow/borrow.html', {'infoBorrowCode': infoBorrowCode()}) def write_read_file(): filepath='app_system/utils/output_QRscan.txt' with open(filepath,'r') as ff: file_content=ff.read() file_content=file_content.strip() return file_content def infoBorrowCode(): file_content=write_read_file() books=apps.get_model('app_common','Book') items_book=books.objects.all() for i in items_book: if(i.label == file_content): return redirect('info-borrow/') return "doesn't exist" def infoBorrow(request): print("dhskld") return render(request,'app_system_borrow/info-borrow.html') This is borrow.html: {% extends "base_system.html" %} {% block title %}CONTILIB{% endblock title %} {% block content %} <div class="interaction-container"> <div class="bot-interaction"> <p>Please scan the <b>QR code</b> of the book.</p> </div> </div> {% endblock content %} {{ infoBorrowCode }} This is urls.py: urlpatterns = [ path("favicon.ico",RedirectView.as_view(url=staticfiles_storage.url("img/avicon.ico"))), path('', views.borrowBook, name="borrowURL"), path('info-borrow/', views.infoBorrow), ] I put some prints in infoBorrowCode() function from views.py to see if the function is called and it is, but after return redirect('info-borrow/'), the print from infoBorrow(request) function doesn't work. It doesn't print anything. So, I think my version isn't good. Can someone exaplin what I'm doing wrong? Please.. Or if there is another option for it.. -
Twilio Incoming SMS Webhook for Admin Access URL
I have configured and have the code written out in my Django app to integrate Twilio SMS sending and receiving. It is successfully sending messages. However, the problem I'm coming across is that the public facing URL I have to communicate with the webhook and TwiML is only accessible for the admin so you have to have a certain authentication to access the messaging dashboard (where the messages are coming in). I'm not sure how to configure this in Twilio I was wondering how I can configure this webhook in Twilio to ensure a user can respond via SMS from their phone and the message will display in the messaging dashboard within the app. I'm not super familiar with Twilio or this situation so any help would be greatly appreciated. Thanks in advance! -
why im getting invalid client error while trying to post in postman
hi i was trying to post in postman using some parameters like client_id and client secret and token which i got it from Facebook[enter image description here][1] developer app `hi i was trying to post in postman using some parameters like client_id and client secret and token which i got it from Facebook[enter image description here][1] developer app ` #here is my reqest url:http://localhost:8000/api/social/convert-token?grant_type=convert_token&client_id=sdklhsjgvdshfuahhddkaj37637utydew7&client_secret=dgshjhsdfkgaskflj8363589klsskjnlksfjnljhfjmj83889ij&backend=facebook&token=lkdfjlkjhdsfkljhbdsncvkjdsh763uhkdjcbgjhxsgckjdsh7ytfgklfclkfoit76ejvmljfdlkjndsi736uihd #postman [1]: https://i.stack.imgur.com/lMQD8.png #also my setting.py from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-0-4)4j%h!n^v@h0fhyk*7b&-za)tliaptb^kqs$5#+=3tns%=+' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'coreapp', 'cloudinary', 'oauth2_provider', 'social_django', 'rest_framework_social_oauth2', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'foodhub.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] WSGI_APPLICATION = 'foodhub.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', … -
How to relate multiple models to a single model in Django?
I want to store all the data related to a specific device, and I called the model that stores that information File. But for example a device with Motherboard, have multiple fields only related to the motherboard(model, brand, serie's number), and so on with the cpu, gpu, mouse, etc. Is there a way to include multiple models inside a model and create a form that join all of them inside the File model? Like this: class File(models.Model): institute = models.CharField(max_length=200) motherboard = models.ForeignKey(Motherboard, on_delete = models.CASCADE) cpu= models.ForeignKey(Cpu, on_delete = models.CASCADE) The problem I having with this aproach is that the create view just showed me a dropdown list in the motherboard and cpu fields, waiting for me to select one of the already existing ones, the expected behavior is the view displaying a form for each of the models and be able of see all the information as a whole under the File model. -
Get all children of self-referencing Django model in nested hierarchy
Introduction We’re currently working on a Django REST Framework project. It connects to a Postgres database that holds some hierarchical (tree structure) data, that goes a number of levels deep. We should offer an endpoint for GET requests that returns the entire nested tree structure (parent, children, grandchildren etc.) when no parameter is offered. ATTENTION: Please do not mark this as a duplicate straight away, without reading the complete question. There are already very similar questions and I already tried the answers to those. I mention these in my post and what problems I face when trying these. Sample data The table below shows the sample data of regions, where each region can have a parent, indicating the hierarchy of regions. In this example, the hierarchy is three levels deep (world>continent>country). But in reality, the tree could go much deeper, having an unknown number of levels (world>continent>country>province>city>neighborhood>etc.). id region parent_region_id 1 world NULL 2 europe 1 3 asia 1 4 africa 1 5 belgium 2 6 germany 2 7 spain 2 8 japan 3 9 indonesia 3 10 vietnam 3 11 tanzania 4 12 egypt 4 13 senegal 4 Our goal The JSON output shown below is what we try … -
Change the user input on django change form before sending it to the database
I have a model that has a uuid representing a certain region. There is a short name for the regions and their respective uuid, this is stored in a csv currently. Is there a way to allow an admin to use the short name instead of the uuid when editing a record, but the uuid is what is actually used in the database? Current: Current edit form Desired: Desired edit form -
Django rest framework Like Function
in django, I want to write a function that deletes the likes if the current user has liked that post before and if so, how can I do this. This is my models.py class Like(models.Model): created_by = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) def __str__(self): return self.created_by.username This is my serializers.py class LikeSerializer(serializers.ModelSerializer): created_by = serializers.StringRelatedField() post = serializers.StringRelatedField() post_id = serializers.IntegerField() class Meta: model = Like fields = ('__all__') This is my views.py class LikesView(viewsets.ModelViewSet): queryset = Like.objects.all() serializer_class = LikeSerializer def perform_create(self, serializer): serializer.save(created_by=self.request.user) This is my urls.py from django.urls import path,include from .views import ( PostView, PostView_View, LikesView, CommentView ) from rest_framework import routers router = routers.DefaultRouter() router.register('likes', LikesView) router.register('post', PostView) router.register('comment', CommentView) urlpatterns = [ ] + router.urls -
How to perform the Django unit test more efficiently on its python complex classes and functions?
I have gone through the Django test case documentation. But only found the case of the simple basic. https://docs.djangoproject.com/en/4.1/topics/testing/overview/ I will be grateful if someone enlightens me with advanced know-how related to unit tests and pytest. -
Cannot makemigrations on Django Settings already configured error
I'm a new django developer and I recently started a project, and am trying to get the database up and running. For background: we are using a mysql database for storage, and the settings are configured for it. Using an Unbuntu DO server. I have also been using the virtual environment to run the commands below. When we initially created the project we ran the makemigrations command, which populated the database with django tables, but not the Models, as we had not made any Models yet. I've now uploaded the Model code, however I could not make any new migrations, I got the error RuntimeError("Settings already configured"). According to this tutorial which I was following (https://www.geekinsta.com/how-to-customize-django-user-model/) some errors are normal and required me to delete and recreate the mysql database (which I did, it has the same name), and clear past migrations (the app/migrations/pycache is now empty). However I'm still experiencing the same error ("Settings already configured"). How can I fix this? I need to successfully run the makemigrations and migrate commands to populate the database. The new database and pycache are empty after I attempted the commands again. Thanks for any and all help. -
Token expiry error when using SimpleJWT TokenVeryifySerializer to return user data
I have a backend API app that uses DRF and SimpleJWT as the Auth engine. The React front-end that consumes the auth API requires an end-point that will accept an access token, verify it and return the token object and associated user object. I am looking to extend SimpleJWT's existing TokenVerifySerializer to do this as it already contains the verify and blacklist logic. I'm hitting a wall when trying this as I keep receiving a Token is invalid or expired error even if the token is valid Any pointers to where the problem may be would be greatly appreciated! Code is as follows: # apiauth/serializer.py from django.contrib.auth.models import User from django.apps import apps from django.contrib.auth.password_validation import validate_password from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from rest_framework import serializers from rest_framework.validators import UniqueValidator from rest_framework_simplejwt.serializers import TokenObtainPairSerializer, TokenVerifySerializer from rest_framework_simplejwt.settings import api_settings from rest_framework_simplejwt.tokens import RefreshToken, SlidingToken, UntypedToken, AccessToken if api_settings.BLACKLIST_AFTER_ROTATION: from rest_framework_simplejwt.token_blacklist.models import BlacklistedToken class MyTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) token['username'] = user.username token['email'] = user.email return token class TokenUserSerializer(TokenVerifySerializer): token = serializers.CharField() def validate(self, attrs): access_token = UntypedToken(attrs["token"]) if ( api_settings.BLACKLIST_AFTER_ROTATION and apps.is_installed("rest_framework_simplejwt.token_blacklist") ): jti = access_token.get(api_settings.JTI_CLAIM) if BlacklistedToken.objects.filter(token__jti=jti).exists(): raise ValidationError("Token is blacklisted") token = AccessToken(access_token) user = User.objects.get(access_token['user_id']) … -
Django annotate a list of integers (not just one integer)
Yes, this below creates me an extra column in the results table, but I only get to have it with a single value (47) I choose that number for demo purposes, not a list of values. Of course, that added list would have to be iterated in the resulting table. Money.objects.filter(viitenumber__in=lista).annotate(mycolumn=Value(47, output_field=IntegerField())) Actually I artificially created that list in Python because I don't know how or if the following thing can be done: in column 1 i have a list of values for example, 1,2,3,4 etc going down for every row. Then the next column would have the addition of those values 1 plus 2 would give 3, 3 plus 3 would give 6 and 6 plus 4 would give 10. like this 1 1 2 3 3 6 4 10 I am at loss as to whether I am close by just annotating the list or there is some function in Django that gets me the second column. I got that cumulated values by looping like in a factorial. -
I keep getting this error massage NoReverseMatch at /
I try to run this code but I get this error NoReverseMatch at / Reverse for 'all-posts' not found. 'all-posts' is not a valid view function or pattern name. and I think my code is okay, here's a bit of it My urls.py from django.urls import path from . import views app_name = "blog" urlpatterns = [ path("", views.index, name="home"), path("all_posts", views.all_posts, name="all-posts"), path("<str:tag>", views.sort_post, name="sorted") ] here's my views.py from django.shortcuts import render from .models import Auhtor, Post, Caption def index(request): return render(request, "blog/index.html") def all_posts(request): all = Post.objects.all() return render(request, "blog/all.html", {"all": all}) def sort_post(request, tag): sort = Post.objects.filter(tag__caption=tag) return render(request, "blog/sorted.html", {"sorted": sort}) and here's my all.html {% extends "blog/base.html" %} {% load static %} {% block title %} My Blog {% endblock %} {% block content %} <div class="nav"> <ul> <a href="{% url "all-posts" %}">All posts</a> </ul> </div> {% endblock %} -
How to make query of each parent only three 0r four child objects get in Django?
I have a list of videos which are belong from some of channels. I want to get only three videos per channel and pass as return value. My code is slice the list of videos not for all channel it's get only three objects. But i want to get each channel of three videos. I don't understand how can i do that... def each_channel_three_videos(request): videos = video.YTVideo.objects.select_related('channel')\ .filter(channel__category__slug='vlogs')\ .order_by('-per_sec_views')[:3] context = { 'videos': videos, } return render(request, 'videos.html', context) -
django Import-export. How can I check if one of the sku wish are going to be imported exist, that way it not going to create a new product but updated
#admin.py from django.contrib import admin from .models import Product from import_export import resources from import_export.admin import ImportExportModelAdmin class ProductResource(resources.ModelResource): class Meta: model = Product class ProductAdmin(ImportExportModelAdmin, admin.ModelAdmin): search_fields = ['name','sku','parent','family'] list_display = ('id','sku','manufacturer','name','short_description','cost','price','price2','parent','family','nla',) list_filter = ('manufacturer',) resource_class = ProductResource admin.site.register(Product, ProductAdmin) -
How to test model labels in Django?
I have the following model.py from django.db import models class Url(models.Model): short_url = models.CharField(max_length=255) original_url = models.CharField(max_length=255) clicks = models.IntegerField(default=0) created_at = models.DateTimeField('date created', auto_now_add=True) updated_at = models.DateTimeField('date updated', auto_now=True) class Click(models.Model): url = models.ForeignKey(Url, on_delete=models.CASCADE, related_name='related_clicks') browser = models.CharField(max_length=255) platform = models.CharField(max_length=255) created_at = models.DateTimeField('date created', auto_now_add=True) updated_at = models.DateTimeField('date updated', auto_now=True) and in the tests/test_models.py from django.test import TestCase from heyurl.models import Url, Click from heyurl.views import short_url class TestModels(TestCase): @classmethod def setupTestdata(cls): Url.objects.create(short_url='eOlKf', original_url='https://www.google.com', clicks= 2) #Figuring out how to test each label def test_short_url_label(self): field_label = Url.objects.get() self.assertEqual(field_label, 'short_url') So basically I would like to know how can I validate my model labels through unit tests in test_models.py What should I use in place of field_label to be able to make use of assertEqual() ? -
expected 4 columns but found 3 - filling the rest with NULL and INSERT failed: datatype mismatch
Currently, I am working on a project and trying to use both Django and SQLite with reference from this video tutorial https://youtu.be/vs6dXL9Wp7s. After performing the .import I keep having 2 errors one is expected 4 columns but found 3 - filling the rest with NULL and the other is INSERT failed: datatype mismatch. errors I have checked my models.py along with my csv file csv and have done everything I can to troubleshoot this issue but still unable to get it fixed. I am new to Django and SQLite, could someone help me with this or suggest what other things I can do? Thank you. Here are my other codes: models.py from django.db import models from django.utils.translation import gettext as _ class reviews (models.Model): reviewer = models.CharField(_("Reviewer Name"), max_length=255) rate = models.CharField(_("Rating"), max_length=255) rw = models.CharField(_("Review"), max_length=255) 0001_inital.py from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='reviews', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('reviewer', models.CharField(max_length=255, verbose_name='Reviewer Name')), ('rate', models.CharField(max_length=255, verbose_name='Rating')), ('rw', models.CharField(max_length=255, verbose_name='Review')), ], ), ] -
Django Admin Dashboard and Views
I am new to Django framework and Django Rest Framework. In views.py file, I have added two class based REST APIs, one is derived from generic.ListCreateAPIView and the another one is derived from generic.RetrieveUpdateDestroyAPIView. Similarly in Django Framework based web application, in views.py file I have added class based views derived from generic.ListView and generic.DetailView. My question is when executing localhost:8000/admin the app is displayed in the browser , I am able to do CRUD operations, would the admin dashboard actions call functions or API in Views.py file or not? In admin.py file we are registering only model objects. -
Creating function to call api for pagination is calling duplicate value int
I am building a simple app in react and django in which I am accessing API and paginating in the backend. The Problem is that, I want to make two calls on per page click, for example - If user clicked on page 1 then I am trying to make api call with page &page=1 and &page=2. And If user clicked on page 2 then make api call &page=3 and &page=4 and If user clicked on page 3 then make api call &page=5 and &page=6 But the problem is that When user is on page 1st then it is making api calls (page 1 and 2) finely But when User moves to page 2 then it is calling api with &page=2 and &page=3 instead of &page=3 and &page=4. I want to call api for next two pages. views.py class MakeApiCall(APIView): def get(self, *args, **kwargs): current_page = self.request.query_params.get('current_page') current_page = int(current_page) for index in range(2): url = "https://api.punkapi.com/v2/beers?page=" + str(current_page) call_api = requests.get(url) print(call_api.url) current_page += 1 When I run above function with current_page = 1 then It is calling api with page=1 and page=2 but when I call current_page = 2 then It is calling again with page=2 and page=3 … -
How to graph Python code, on the web and on Windows
I wrote a code for practice and published it on Github. Now I want to make it online, how can I run it in the Windows operating system and the website instead of running it in the command line environment? (taking input and displaying output in a graphical environment) that the user can easily work with. What library should I use and how much should I change in my code? my code: https://github.com/rezaheidary82/colson/ -
can't copy packages' info from virtual environment
idk why but this command doesn't work: pip freeze > requirements.txt the error is: The system cannot find the file specified but in fact, my terminal does create a file requirements.txt just doesn't copy the info about the used packages All the steps I followed: Activated venv created a github repo used git init created a .gitignore file used the above freeze command -
Bootstrap 5: Navbar Won't Expand when toggle clicked
I'm really new to bootstrap and HTML and when I use the HTML provided by bootstrap 5 for the search bar and toggler icon when the window is small, I'll see the toggler icon but it won't expand when clicked which is strange because it will on the example provided on bootstrap's website. This is my HTML file I'm using that has the navbar: <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <title>Book Store</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="container-fluid"> <a class="navbar-brand">Manga Book Store</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="{% url 'home' %}">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Dropdown </a> <ul class="dropdown-menu"> <li><a class="dropdown-item" href="#">Action</a></li> <li><a class="dropdown-item" href="#">Another action</a></li> <li><hr class="dropdown-divider"></li> <li><a class="dropdown-item" href="#">Something else here</a></li> </ul> </li> <li class="nav-item"> <a class="nav-link disabled">Disabled</a> </li> </ul> <div class="collapse navbar-collapse justify-content-center"> <form class="d-flex" role="search" method=POST action="{% url 'search_manga' %}"> {% csrf_token %} <input class="form-control me-2" type="search" placeholder="Search …