Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
social-auth-app-django Google Login and React-Native
I'm using the social-auth-app-Django library on my Django Rest API (DRF) to authenticate users with social providers. I am using the expo-auth-session library (though this could be changed) in my React Native frontend to open a webbrowser instance for the client to use to log in with social providers (i.e. google). The issue is that once the login is succesful, the small window from the webbrowser instance instead of closing, redirects back to the App in the small browser window. settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'] , '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', ], }, }, ] AUTHENTICATION_BACKENDS = ( 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', ) for key in ['GOOGLE_OAUTH2_KEY', 'GOOGLE_OAUTH2_SECRET', ]: exec("SOCIAL_AUTH_{key} = os.environ.get('{key}')".format(key=key)) SOCIAL_AUTH_LOGIN_REDIRECT_URL = 'http://localhost:19006/' urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('oauth/', include('social_django.urls', namespace='social')), ] index.tsx const signInGoogle = async () => { const redirectUri = AuthSession.makeRedirectUri({ useProxy: true, }); const result = await WebBrowser.openAuthSessionAsync( `http://localhost:8000/oauth/login/google-oauth2?next=${redirectUri}`, redirectUri ); console.log(result); }; Once the login is succesful, the small window from the webbrowser instance instead of closing, redirects back to the App/WebApp in the small browser window. -
using reverse url in javascript
I need to add event listener to standard django select field. The listener will (in the future) do htmx.ajax call ( https://htmx.org/api/#ajax ) urls.py from django.urls import path from .views import mailtemplate_GetSchema, refresh_schema from .views import surat_schema_table urlpatterns = [ path('htmx/surat_schema_table/<str:template_id>', surat_schema_table, name='surat_schema_table'), ] currently I have a test template. This template will not do ajax call, just display final url tobe called form template ( surat_form_htmx.html ) {% extends "admin/change_form.html" %} {% block after_field_sets %} <!--- add htmx --> <script src="https://unpkg.com/htmx.org@1.6.0"></script> <style> /* DivTable.com */ .divTable{ display: table; width: 100%; } .divTableRow { display: table-row; } .divTableCell, .divTableHead { border: 1px solid #999999; display: table-cell; padding: 3px 10px; } .divTableHeading { display: table-header-group; font-weight: bold; } .divTableFoot { background-color: #EEE; display: table-footer-group; font-weight: bold; } .divTableBody { display: table-row-group; } </style> <!-- EOF evt listener id_template --> Obj ID: <input id="loaded_object" id="loaded_object" type="text" size="20" readonly {% if not add %} value="{{ obj_id }}" {% endif %}> Selected Template: <input id="selected_template" name="selected_template" type="text" size="20" readonly > url: <input id="call_url" name="call_url" type="text" size="20" readonly > <script> const selectElement = document.querySelector("#id_template"); selectElement.addEventListener('change', (event) => { var result = document.getElementById("id_template").value ; var url_final={% url surat_schema_table result %} ; document.getElementById('selected_template').value = result; document.getElementById('call_url').value = … -
Is it possible in Django model tables to perform arithmetic operations on a record in another table?
How can I fill in a row or add a second table? I need to perform calculations with the last row from the first table and send the results to the second table. This is something reminiscent of processing data in two DataFrame . How can I add a table of values to the model after performing calculations on the data from the last row from another table model? Or is this only possible with the participation of the DataFrame functionality? class Model_1(models.Model): name_1 = models.IntegerField() name_2 = models.IntegerField() name_3 = models.IntegerField() name_4 = models.IntegerField() class Model_2(models.Model): name_5 = models.IntegerField() name_6 = models.IntegerField() queryset = Model_1.objects.all() values_m1 = queryst.name_1 * queryst.name_2 / queryst.name_3 - queryst.name_4 queryset = Model_2.objects.all() values_m2 = queryst.name_5 = values_m1 -
I have 2 index.html files in django project, how to show direct separately
I have 2 index.html files in django project, but in different apps. How can i show direct separately for each of them? def index(request): return render(request, 'index.html') -
Permit creation only if model is subclass of mixin
I would like to allow the creation of a comment only to those models that are sub-classing a specific mixin. For example, a Post model will have a reverse GenericRelation relation to a Comments model. The comments model is using a custom content types mechanism implemented on top of django's due to the fact that the project uses sharding between multiple databases. The reverse relationship from Post model to Comments is needed to be able to delete Comments when a Post is also deleted. Putting a simple coding example of what I would like to achieve: class Post(models.Model, HasCommentsMixin): some_fields = .... class HasCommentsMixin(models.Model): has_comments = GenericRelation('comments.Comment') class Meta: abstract = True What I would like would me a way to say inside a permission check of a Model: if class is subclass of HasCommentsMixin, allow the creation of a comment. So for the Post model, comments can be created. But if it's not a subclass the Mixin, comments should not be allowed. I hope I have provided a description that makes sense. I cannot share real code due to product license and protection. Thank you. -
Error in trying to connect Model to ModelForm in Django
I'm learning Django and am trying to make a request form to fill by using Django and an MySQL database and i am encountering issues trying to connect models.py to forms.py making a ModelForm with a database and table i have already created. It returns this error specifically (envworld) C:\Seen\Documents\envworld\myweb>python manage.py makemigrations Traceback (most recent call last): File "C:\Seen\Documents\envworld\myweb\manage.py", line 22, in <module> main() File "C:\Seen\Documents\envworld\myweb\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Seen\Documents\envworld\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Seen\Documents\envworld\lib\site-packages\django\core\management\__init__.py", line 420, in execute django.setup() File "C:\Seen\Documents\envworld\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Seen\Documents\envworld\lib\site-packages\django\apps\registry.py", line 124, in populate app_config.ready() File "C:\Seen\Documents\envworld\lib\site-packages\django\contrib\admin\apps.py", line 27, in ready self.module.autodiscover() File "C:\Seen\Documents\envworld\lib\site-packages\django\contrib\admin\__init__.py", line 50, in autodiscover autodiscover_modules("admin", register_to=site) File "C:\Seen\Documents\envworld\lib\site-packages\django\utils\module_loading.py", line 58, in autodiscover_modules import_module("%s.%s" % (app_config.name, module_to_search)) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2544.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Seen\Documents\envworld\myweb\formsite\admin.py", line 2, in <module> from .forms import RequestForm File "C:\Seen\Documents\envworld\myweb\formsite\forms.py", line 12, in <module> request = Request_Form.objects.get(pk=1) File "C:\Seen\Documents\envworld\lib\site-packages\django\db\models\manager.py", line 85, … -
Django Requests and Concurrency
I'm a little bit confused as to a few concepts regarding Django and concurrency. Suppose two users append data to the database or make a query at the same time. How do I determine what data to render for the user? I know each model has an id, but how is that associated with the user? Is this done mainly through the primary key field which you can add to Django views, or is this already done using Django sessions, and thus no need for management of primary keys or Django model ids? I've been researching for hours but I still don't understand this concept. -
Why individually rendered form fields not posting in Django?
I have a class based UpdateView that works fine if I render the form as {{ form.as_p }}. It updating the values, but looks bad. If I try to render the fields individually it does not updating the values. I can't figure out how to fix it, I'm not so familiar with class based views. I don't think there is a validation error (i don't know how to check it in class based views) because {{ form.as_p }} works well. Thank you in advance if someone can help me out! models.py class LeaderFeedback(models.Model): def __str__(self): return str(self.employee) employee = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name="employed") leader = models.ForeignKey(User, on_delete=models.CASCADE, related_name="employer_leader") goals01 = models.CharField(max_length=100, null=True, blank=True) goals01_deadline = models.CharField(max_length=30, null=True, blank=True) goals01_value = models.IntegerField(null=True, blank=True) leader_comment = models.CharField(max_length=500, null=True, blank=True) views.py class UpdateLeaderFeedbackView(SuccessMessageMixin, UpdateView): model = LeaderFeedback form_class = PeriodicLeaderFeedbackForm template_name = 'performance/periodic/leader_feedback_edit.html forms.py class Meta: model = LeaderFeedback fields = '__all__' goals_value =( (1, "Nem teljesült"), (2, "Részben teljesült"), (3, "Megfelelő"), (4, "Maximálisan teljesült"), ) widgets = { 'goals01_value': forms.RadioSelect(choices=goals_value), 'leader_comment': forms.Textarea(attrs={"rows":"3", 'class': 'form-control'}), urls.py app_name = 'performance' urlpatterns = [ ... path('periodic/leader_feedback_edit/<pk>', login_required(UpdateLeaderFeedbackView.as_view()), name='update_leaderfeedback'), ... leader_feedback_edit.html <div class="card shadow p-2 my-2"> <div class="row"> <div class="col-md-5"> <h6 class="">Cél 1:</h6> {{ object.goals01 … -
I need to Prefetch data but only last in django
class AppliedEvent(models.Model): event_type = models.ForeignKey(EventType, on_delete=models.CASCADE, related_name='applied_events', null=True) seedbed = models.ForeignKey(Seedbed, on_delete=models.CASCADE, null=True, related_name='applied_events') seed = models.ForeignKey(Seed, on_delete=models.CASCADE, related_name='applied_events', null=True) user = models.ForeignKey(UserModel, on_delete=models.CASCADE, related_name='applied_events', null=True) class AppliedEventTime(models.Model): start_time = models.DateTimeField() end_time = models.DateTimeField() event = models.ForeignKey(AppliedEvent, on_delete=models.CASCADE, related_name='times') applied_by = models.ForeignKey(UserModel, on_delete=models.CASCADE, related_name='applied_times', null=True) User have ability to add new event time by creating new AppliedEventTime instance. class AppliedEventMixin: request: Any def get_queryset(self) -> QuerySet: return AppliedEvent.objects.filter(user_id=self.context.request.user).select_related( 'user', 'event_type', 'seedbed', 'seed' ).only('user__username', 'event_type__name', 'seedbed__id', 'seed__id').prefetch_related( 'times' ) This is my query set mixin for django-extra controller @api_controller('/applied_event', auth=JWTAuth(), permissions=[IsAuthenticated]) class AppliedEventController(AppliedEventMixin): @route.get('/applied_event/{event_id}', tags=['applied_event'], response=AppliedEventOutSchema) def event_by_id(self, event_id: int): event = get_object_or_404(self.get_queryset(), pk=event_id) return event This is controller for API and point. class EventTypeNameSchema(Schema): id: int name: str AppliedEventTimeSchema = create_schema(AppliedEventTime, exclude=['id', 'event'], custom_fields=[('applied_by', UserOutSchema, None)]) class UserOutSchema(Schema): id: int username: str class AppliedEventOutSchema(ModelSchema): event_type: EventTypeNameSchema user: UserOutSchema times: List[AppliedEventTimeSchema] class Config: model = AppliedEvent include = ['id', 'seedbed', 'seed'] This is my schema. my question is, how can i prefetch only latest added AppliedEventTime instance related to AppliedEvent? -
How to display multiple database values in a single input?
I have a small problem for a few hours. I'm working on an app that uses django python. (I'm new to Django) I'm currently working on the Front-end, and I would like to display a first name and last name in an input. This works fine for two separate input but I would like to display the first name and last name in the same input. I do not know how to do <input style="background-color: blue;"{{form.user_first_name}}> Thanks -
Django - How can I collect several item/quantity for one order, and save it with one submit of form
I have this model: class ItemsInExternalOrder(models.Model): order = models.ForeignKey(ExternalOrder, on_delete=models.DO_NOTHING) item = models.ForeignKey(Item, on_delete=models.DO_NOTHING) quantity = models.IntegerField() created_at = models.DateTimeField(auto_now=False, auto_now_add=True) updated_at = models.DateTimeField(auto_now=True, auto_now_add=False) def __str__(self) -> str: return " ".join([f'{self.order}', f'{self.item}', f'{self.quantity}']) and the form : class ItemsInExternalOrderForm(forms.ModelForm): class Meta: model = ItemsInExternalOrder fields = ["order", "item", "quantity"] and HTML: <form action="" method="POST">{% csrf_token %} {{ form.as_p}} <input type="submit" value="Save"> </form> How can I collect several item/quantity for one order, and save it with one submit of form. I saw some examples with JS but I wonder if it is possible with Django Forms only and HTML. Thanks in advance, and apologies if this question is already asked, I just cant find answer without JS if it is possible. -
How to implement registration for Junior levels of users for my project
I'm developing an ecommerce related project in Django rest framework. In my project, there are three types of users, primary user, junior level user and clients. i will keep the registration open for primary users and the next level (junior level and clients) users should only be registered by primary users. primary user will create the credentials and send the invite for next level of users. I've no proper ideas for this. can anyone suggest some good ideas for this ? -
How to use Celery and/or Redis or RabbitMQ for sending email?
I need to implement sending emails via Celery and/or Redis or RabbitMQ. I have a todo app, with various model instances and one of them is done which is booleanfield. And when the task is to send emails to the user when the task is done or undone. So what should i do ? What do i need to show you in my code in order to be able help me? Thanks in advance, would be glad if you provide some tutorials, articles, docs for better understanding -
(1062, "Duplicate entry 'admin1' for key 'username'")
models.py class CustomUser(AbstractUser): user_type_data=((1,"HOD"),(2,"Staff"),(3,"Student")) user_type=models.CharField(default=1,choices=user_type_data,max_length=10) class palabout(models.Model): user = models.ForeignKey(CustomUser, blank=True, null=True, on_delete=models.SET_NULL) profileImage = models.FileField() username = models.CharField(max_length=30) email = models.EmailField(max_length=100) password = models.CharField(max_length=100) fname = models.CharField(max_length=30) lname = models.CharField(max_length=30) gender = models.CharField( max_length=1, choices=(('m', ('Male')), ('f', ('Female'))), blank=True, null=True) dob = models.DateField(max_length=8) forms.py class palForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model=palabout fields =['username','password','email','fname','lname','dob','gender','profileImage'] views.py from .forms import palForm def add_form(request): form = palForm(request.POST, request.FILES) username=request.POST.get("username") email=request.POST.get("email") password=request.POST.get("password") if request.method == "POST": form = palForm(request.POST , request.FILES) user=CustomUser.objects.create_user(username=username,password=password,email=email,user_type=1) if form.is_valid() and user.is_valid(): try: form.save() user.save() messages.success(request,"Successfully Added") return render(request,"home.html") except: messages.error(request,"Failed to Add") return render(request,"home/pal-form.html") else: form=palForm() return render (request,"home/pal-form.html",context={"form":form}) Error: The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\charu\Anaconda3\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\charu\Anaconda3\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\charu\OneDrive\Desktop\cha\school social\myschool\polls\views.py", line 19, in studentreg user=CustomUser.objects.create_user(username=username,password=password,email=email,user_type=3) File "C:\Users\charu\Anaconda3\lib\site-packages\django\contrib\auth\models.py", line 161, in create_user return self._create_user(username, email, password, **extra_fields) File "C:\Users\charu\Anaconda3\lib\site-packages\django\contrib\auth\models.py", line 155, in _create_user user.save(using=self._db) File "C:\Users\charu\Anaconda3\lib\site-packages\django\contrib\auth\base_user.py", line 68, in save super().save(*args, **kwargs) File "C:\Users\charu\Anaconda3\lib\site-packages\django\db\models\base.py", line 812, in save self.save_base( File "C:\Users\charu\Anaconda3\lib\site-packages\django\db\models\base.py", line 863, in save_base updated = self._save_table( File "C:\Users\charu\Anaconda3\lib\site-packages\django\db\models\base.py", line 1006, in _save_table results = self._do_insert( File "C:\Users\charu\Anaconda3\lib\site-packages\django\db\models\base.py", line … -
VSCode: [Django] How to navigate to the desired file via urls includes ike PyCharm
enter image description here How to realize it so that when I click on urls inside includes, it moves to the desired file like PyCharm I've already installed vscode extensions Pylance and Django -
NOT NULL constraint failed: tickets_category.name
I am creating a ticket app in my django project. When I try to create a ticket the NOT NULL constraint failed: tickets_category.name error shows up. I'm not sure why the value for category_name field won't pass correctly. How do I proceed? any help is much appreciated. Here's what i have so far models.py class Category(models.Model): name = models.CharField(max_length=200, null=True) def __str__(self): return self.name class Ticket(models.Model): STATUS = ( (True, 'Open'), (False, 'Closed') ) PRIORITIES = ( ('None', 'None'), ('Low', 'Low'), ('Medium', 'Medium'), ('High', 'High') ) TYPE = ( ('Misc', 'Misc'), ('Bug', 'Bug'), ('Help Needed', 'Help Needed'), ('Concern', 'Concern'), ('Question', 'Question') ) host = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True, related_name='host') category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name='category') name = models.CharField(max_length=200, null=True) status = models.BooleanField(choices=STATUS, default=True) priority = models.TextField(choices=PRIORITIES, default='None', max_length=10) type = models.TextField(choices=TYPE, default='Misc', max_length=15) description = RichTextField(null=True, blank=True) # description = models.TextField(null=True, blank=True) participants = models.ManyToManyField(CustomUser, related_name='participants', blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-updated', '-created'] def __str__(self): return self.name views.py view for creating a ticket def createTicket(request): form = TicketForm() categories = Category.objects.all() if request.method == 'POST': category_name = request.POST.get('category') category, created = Category.objects.get_or_create(name=category_name) ticket = Ticket.objects.create( host = request.user, category=category, name=request.POST.get('name'), status=request.POST.get('status'), priority=request.POST.get('priority'), type=request.POST.get('type'), description=request.POST.get('description'), ) … -
Django problema de vistas
Hola tengo un problema en django, hice un proyecto personal de un inventario. El problema es que entrando a un link directo, cualquier usuario registrado puede ver los productos de otro usuario http://000000/products/viewproduct/1, esta vista es para ver un producto, pero si cambio el numero al final, que es el id del producto en la base de datos puedo ver el que sea siempre y cuando exista, por ejemplo mi amigo tiene 5 productos con las id del 5 al 10 y yo solo del 1 al 4. si yo inicio sesion en mi cuenta y pongo http://000000/products/viewproduct/5 <- ahi le cambie el numero de id del producto y ese no es mi producto pero aun asi lo puedo consultar. Ese es mi problema y ya intente usando {% if request.user.is_authenticated %} pero no sirve. your text class ViewProduct(LoginRequiredMixin, DetailView): model = Product template_name = "products/view.html" context_object_name = "product" Esta es la vista creada -
Django DRF Model doesn't show foreign keys in admin panel
I have a model in my Django application for review. This model has two foreign keys to the product and user models. But when I go to the admin panel and try to add a new review I don't see the review models dropdown select for the foreign keys. I'm expecting to see the foreign keys fields rendered in my admin panel as dropdown selects like in the blue box in the picture below. Screenshot of my admin panel to add a new order object But the admin panel doesn't show those fields. It only shows the name, rating, and comment fields. Screenshot of my admin panel to add a new reivew object Here is my review model. class Reviews(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True), product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True), name = models.CharField(max_length=350, null=True, blank=True) rating = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True, default=0) comment = models.TextField(null=True, blank=True) createdAt = models.DateTimeField _id = models.AutoField(primary_key=True, editable=False) def __str__(self): return str(self.rating) -
I have a class with a variable called available and other isActive
i'm just starting in djando. I have a class with a variable called available = models.CharField(max_length=20) and other isActive = models.BooleanField(default=True). I'd like to be able to get the word "unavailable" in the available field if isActive is false. thanks listingData = Listing.objects.get(pk=id) if listingData.isActive == False: Listing.available = "unavailable" -
An admin for model "CustomUser" has to be registered to be referenced by FolderAdmin.autocomplete_fields
I am trying to install django-filer and after following the installation docs(pip install, add to INSTALLED_APPS etc), when I try run my dev server I get the following error in the terminal... ERRORS: <class 'filer.admin.folderadmin.FolderAdmin'>: (admin.E039) An admin for model "CustomUser" has to be registered to be referenced by FolderAdmin.autocomplete_fields. <class 'filer.admin.permissionadmin.PermissionAdmin'>: (admin.E039) An admin for model "CustomUser" has to be registered to be referenced by PermissionAdmin.autocomplete_fields. As visible in the error output. I've extended the Django user model with CustomUser. I have also extended AdminSite to get custom urls in the admin. So perhaps extending these is causing the error. Any possible solution to this? The error says an admin has to be registered and I do have multiple superusers registered. -
detail": "Method \"GET\" not allowed. | Django Rest Framework
I'm following a course on user login and registration and I'm getting this error and I don't know how to fix it detail": "Method \"GET\" not allowed. urls.py from django.urls import path from . import views urlpatterns = [ path('users/login/', views.MyTokenObtainPairView.as_view(), name='token_obtain_pair'), path('users/register/', views.registerUser, name='register'), path('users/profile/', views.getUserProfile, name="users-profile"), path('users/', views.getUsers, name="users"), ] views.py @api_view(['POST']) def registerUser(request): data = request.data user = User.objects.create( first_name = data['name'], username = data['email'], email = data['email'], password = make_password(data['password']) ) serializer = UserSerializerWithToken(user, many=False) return Response(serializer.data) serializers.py class UserSerializer(serializers.ModelSerializer): name = serializers.SerializerMethodField(read_only=True) _id = serializers.SerializerMethodField(read_only=True) isAdmin = serializers.SerializerMethodField(read_only=True) class Meta: model = User fields = ['id', '_id', 'username', 'email', "name", "isAdmin"] def get__id(self, obj): return obj.id def get_isAdmin(self, obj): return obj.is_staff def get_name(self, obj): name = obj.first_name if name == '': name = obj.email return name class UserSerializerWithToken(UserSerializer): token = serializers.SerializerMethodField(read_only=True) class Meta: model = User fields = ['id', '_id', 'username', 'email', "name", "isAdmin", 'token'] def get_token(self, obj): token = RefreshToken.for_user(obj) return str(token.access_token) I'm not sure if this is the problem but I saw someone who said that since in views.py I have the view as @api_view(['POST']) I cant call it in urls.py the way I usually would. I would test that but I dont … -
How can I create authorization with dinamic roles in a Django backend, with the frontend built in React?
I am creating a system that implements authentication and authorization with React in the Frontend and Django. But Ich must implement dinamic roles and don't find how to make authorization in the backend, just in the front. How could I make that? I store the menu elements of the front in the database and based on the role the user create show those elements. But all the enpoints are accessible in the API for a user who have valid credentials for authentication. I'm using simple-jwt and django-restframework. A middleware that'd store the authenticated user and his roles it's something I think would be close to the answer but don't know how to implement it either. I hope someone can help me. Thanks in advance. -
Overwrite Django ImageField to accept absolute URIs as well as files
What ImageField does under the hood , is that is stores the image path as string in the db. I would like to overwrite the field in such a way, that it can accept either a binary image file or absoulte URI path and return the path as string and store it as char in the db. Which method would have to be overwritten to achieve this operation ? thanks -
HTML Email not sending when debug=false in django
I am making a website in which once the user registers for an event they are sent an email for the same confirming that they have registered for the event. Now, the thing is I can send the html mail when DEBUG=True but I am not able to send the html mail when DEBUG=False in Django, neither I am able to detect why is it failing. Attaching code snippet. Thanks for your help! settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = env('EMAIL_USE_TLS') == 'True' EMAIL_HOST = env('EMAIL_HOST') #smtp.gmail.com EMAIL_HOST_USER = env('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD') EMAIL_PORT = env('EMAIL_PORT') #587 views.py try: EventRegistration(event=event_obj, first_name=first_name, last_name=last_name, roll_number=roll_number, phone_number=phone_number, email=email, year_of_study=year_of_study, department=department).save() subject = f"Registration Successfull For {event_name}" html_message = render_to_string("mail related/Register Confirmation.html", context={'image': event_obj.banner_image, 'name': event_name, 'date': event_obj.event_date}) plain_message = strip_tags(html_message) from_email = settings.EMAIL_HOST_USER to_list = [email] send_mail(subject, plain_message, from_email, to_list, html_message=html_message) messages.info(request, 'Successfully registered') except e: messages.warning(request, 'Failed to Register') return render(request, 'main/register.html', context) except Exception: return redirect('events' -
How can I perform calculations from the queryset of one model add them to the fields of another model?
Good day! I have two Django table models. And even the result of the query after the filter operation with the model table. One of these tables contains data that is populated using a Django form. Another table can be filled only with data obtained after performing calculations with data from the first table. How can I fill in a row or add a second table? I need to perform calculations with the last row from the first table and send the results to the second table. This is something reminiscent of processing data in two DataFrame . How can I add a table of values to the model after performing calculations on the data from the last row from another table model? class Model_1(models.Model): name_1 = models.IntegerField() name_2 = models.IntegerField() name_3 = models.IntegerField() name_4 = models.IntegerField() class Model_2(models.Model): name_5 = models.IntegerField() name_6 = models.IntegerField() queryset = Model_1.objects.all() values_m1 = queryst.name_1 * queryst.name_2 / queryst.name_3 - queryst.name_4 queryset = Model_2.objects.all() values_m2 = queryst.name_5 = values_m1