Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
session expires while switching to another app.route in flask
Session expires when the '/mobile-confirmation' app.route runs and the user redirects to login page @app.route("/signup", methods=["GET", "POST"]) def signup(): if request.method == "POST": #SignUp form Insert codes ...... db.execute("SELECT tempcode FROM users WHERE id = %s", [userID]) tmpcode = db.fetchall() sms_soap.send_by_base_number([tmpcode[0][0]], phonenum[0][0], 999999) executor.submit(tempcodecountdown, username) session["user_id"] = userID return redirect("/mobile-confirmation") else: return render_template("signup.html") @app.route("/mobile-confirmation", methods=["GET", "POST"]) @login_required def confirmmobile(): user_id = session["user_id"] if request.method == "POST": enteredcode = request.form.get("tempcode") db.execute("SELECT tempcode FROM users WHERE id = %s", [user_id]) tmpcode = db.fetchall() if enteredcode == tmpcode[0][0]: db.execute("UPDATE users SET activation = %s WHERE id = %s", ['yes', user_id]) mydb.commit() return redirect('/dashboard') else: return render_template("mobileconfirmation.html") and these are session settings @app.after_request def after_request(response): response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" response.headers["Expires"] = 0 response.headers["Pragma"] = "no-cache" return response app.config["SESSION_FILE_DIR"] = mkdtemp() app.config["SESSION_PERMANENT"] = False app.config["SESSION_TYPE"] = "filesystem" app.config["TEMPLATES_AUTO_RELOAD"] = True app.config['SESSION_COOKIE_SAMESITE'] = "None" app.config['SESSION_COOKIE_SECURE'] = True it was working correctly in another ide but now I have this problem on cpanel -
Django - how to retrieve data from two models (at the same time) related with OneToOne relation?
In Django I have two models: class Car(models.Model): model_name = CharField(...) make_name = CharField(...) car_exterior_color= = CharField( CHOICES ) class CarWash(models.Model): car_washed = BooleanField(...) wash_date = DateTimeField(...) added_wax = BooleanField(...) car = models.OneToOneField(Car, on_delete=models.CASCADE, verbose_name="Car washed") I need to show such table in view, that retrieves data from two models: model_name make_name car_ext_col car_washed ? added_wax ? wash date IS Lexus blue Yes No 2023-02-02 G37 Infiniti white No No -- RX Lexus red Yes No 2023-02-02 Corolla Toyota green No No -- Tundra Toyota blue Yes Yes 2023-02-02 Q70 Infiniti yellow Yes Yes 2023-02-03 Civic Honda black Yes No 2023-02-03 Malibu Chevrolet red Yes Yes 2023-02-04 GS Lexus yellow Yes No 2023-02-04 Q30 Infiniti white No No -- What should I write in views.py? How to retrieve data from two models to get table as above? -
hi, i want add search bar to myproject but don't return anything
this view for search: class Search(generic.ListView): model = Blog template_name = 'pages/blog_list_view.html' context_object_name = 'blog' def get_queryset(self): search = self.request.GET.get("q") search_result = Blog.objects.filter( Q(title__icontains=search) | Q(description__icontains=search) | Q(active=True)) return search_result search form in _base.html <form action="{% url 'search' %}" method="get"> <input name="q" type="text" placeholder="Search..."> </form> my model class Blog(models.Model): title = models.CharField(max_length=100) cover = models.ImageField(upload_to='blog_cover/') description = models.CharField(max_length=200) text = models.TextField() author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) active = models.BooleanField(default=False) date_create = models.DateField(auto_now_add=True) date_modified = models.DateField(auto_now=True) def __str__(self): return f'{self.title} : {self.author}' def get_absolute_url(self): return reverse('blog_detail', args=[self.id]) tip: "I use Persian language for search" I tried __icontains and __contains but result was same -
Writing a tuple search with Django ORM
I'm trying to write a search based on tuples with the Django ORM syntax. The final sql statement should look something like: SELECT * FROM mytable WHERE (field_a,field_b) IN ((1,2),(3,4)); I know I can achieve this in django using the extra keyword: MyModel.objects.extra( where=["(field_a, field_b) IN %s"], params=[((1,2),(3,4))] ) but the "extra" keyword will be deprecated at some point in django so I'd like a pure ORM/django solution. Searching the web, I found https://code.djangoproject.com/ticket/33015 and the comment from Simon Charette, something like the snippet below could be OK, but I can't get it to work. from django.db.models import Func, lookups class ExpressionTuple(Func): template = '(%(expressions)s)' arg_joiner = "," MyModel.objects.filter(lookups.In( ExpressionTuple('field_a', 'field_b'), ((1,2),(3,4)), )) I'm using Django 3.2 but I don't expect Django 4.x to do a big difference here. My db backend is posgresql in case it matters. -
Can i make an stackedInline connnection between two model without having any connection between them ? in Django
class Item(models.Model): name=models.CharField(max_length=250) description = model.TextField() class Photo(models.Model): item = models.ForiegnKey(Item) title=models.ChaField(max_length=250) here is admin.py class PhotoInline(admin.StackedInline): model = Photo class ItemAdmin(admin.ModelAdmin): inlines = [PhotoInline] admin.site.register(Item,strong text ItemAdmin) admin.site.register(Photo) i want to have an inline connection between without them having any relationship -
(Django model) How does this Message model works?
So I am following a Youtube video on how to create a chatting app. Then it build a model that I don't understand. Here's the Message model I came across and can't understand how it works. class Message(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user') sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='from_user') recipient = models.ForeignKey(User, on_delete=models.CASCADE, related_name='to_user') body = models.TextField() date = models.DateTimeField(auto_now_add=True) is_read = models.BooleanField(default=False) def send_message(from_user, to_user, body): sender_message = Message(user=from_user, sender=from_user, recipient=to_user, body=body, is_read=True) sender_message.save() recipient_message = Message(user=to_user, sender=from_user, recipient=from_user, body=body, is_read=True) recipient_message.save() return sender_message def get_message(user): users = [] messages = Message.objects.filter(user=user).values('recipient').annotate(last=Max('date')).order_by('-last') # filter by user=the login user, recipient=the sender, the lastest message from each sender, order the lastest message by sender using time for message in messages: users.append({ 'user': User.objects.get(pk=message['recipient']), 'last': message['last'], 'unread': Message.objects.filter(user=user, recipient__pk=message['recipient'], is_read=False).count(), }) return users I understand the different fields of the Message model but I fail to understand why it create two instances of the message model in the send_message() function. One for sender message and another for recipient message. recipient_message = Message(user=to_user, sender=from_user, recipient=from_user, body=body, is_read=True) Then for the recipient_message I'm not clear why the recipient field is set to from_user instead of to_user?? Could anyone please help me with this? I am … -
Getting ERROR "You must provide at least one recurring price in `subscription` mode when using prices."
Hello I am beginner in Django while trying to create Subscription with stripe i am getting error as InvalidRequestError at /stripe/create-checkout-session Request req_M2eko0H9LwXvDz: You must provide at least one recurring price in subscription mode when using prices. This is my views.py code snippet. `checkout_session = stripe.checkout.Session.create( success_url=request.build_absolute_uri(reverse('main:complete') ) + "?session_id={CHECKOUT_SESSION_ID}", cancel_url=request.build_absolute_uri(reverse('main:cancelled_transaction')), client_reference_id=request.user.id if request.user.is_authenticated else None, customer_email = email, payment_method_types=['card'], line_items=[ { 'quantity': 1, 'price_data':{ 'product':'PRODUCT_ID', 'unit_amount':settings.STRIPE_PRICE_ID, 'currency':'INR', # 'recurring':'DAY' } } ], mode='subscription', ) ` I have tried to use https://stripe.com/docs/api/checkout/sessions/create#create_checkout_session-line_items-price_data-recurring in my code. -
How to add reference Parameters in extend_schema decorator in drf-spectacular
I'm using drf-spectacular to generate the swagger/redoc API documentation. I am facing issue in customising the schemas generated. I am trying to generate reference parameter using @extend_schema decorators in drf_spectacular but did'nt get the expected schema. extend_schema - ` from drf_spectacular.utils import extend_schema @extend_schema( parameters=headerParam, responses = {200:Response1,400:errorresponse}, tags = ['User'], )` headerParam - `headerParam = [ OpenApiParameter( name='Accept-Language', location=OpenApiParameter.HEADER, type=OpenApiTypes.STR, description='ISO 2 Letter Language Code', required=True, enum=['en', 'ar'], # default='en', ), OpenApiParameter( name='Accept', location=OpenApiParameter.HEADER, type=OpenApiTypes.STR, description='Type of response you are expecting from API. i.e. (application/json)', required=True, default='application/json', ), ]` The problem I am facing is the schema in drf_spectacular is generating this as below - `"parameters": [ { "in": "header", "name": "Accept", "schema": { "type": "string", "default": "application/json" }, "description": "Type of response you are expecting from API. i.e (application/json)", "required": true }, { "in": "header", "name": "Accept-Language", "schema": { "type": "string", "enum": [ "ar", "en" ] }, "description": "ISO 2 Letter Language Code", "required": true } ],` I want to generate like this - "parameters": [ { "$ref": "#/components/parameters/Accept" }, { "$ref": "#/components/parameters/Accept-Language" } ],` Thank you and Appreciate for the help in Advance :) I have done R&D but didn't find anything related to this. -
i am getting 405 error for get method in my django api, instead, i want a default message for get method
For django API, which we have written, post method is allowed but instead of get method, i am getting 405 error, but instead i want some default message like- "error". I am sharing my code. Please let me know if anyone can help. @api_view(['GET']) @permission_classes([AllowAny]) -
how change database's port dynamically(django)
i have a django project that it should have ability to change the database's port dynamically for security reasons. for example there should be a template like ( port= ) and the administrator should enter a port and change the default one. how to do this? -
500 error on django channels send message to group
I have the following Django channels consumer but when I try to send data to the stocks group، it returns a 500 error. Also, I don't get any error logs. Here is the consumer: class AuthRequiredConsumer(JsonWebsocketConsumer): def connect(self): user = self.scope['user'] print(isinstance(user, AnonymousUser)) if isinstance(user, AnonymousUser): raise DenyConnection("authentication required") self.accept() class ChatConsumer(AuthRequiredConsumer): groups = ['stocks'] channel_layer_alias = "stocks" def stocks_data(self, event): print(event) return self.send_json({'message': event['text']}) def receive_json(self, content, **kwargs): channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( "stocks", { "type": "stocks.data", "text": "Hello there!", }, ) message = content["message"] self.send_json({"message": message}) Also, I use this middle to authenticate users by the token: @database_sync_to_async def get_user(token_key): try: token = Token.objects.get(key=token_key) return token. user except Token.DoesNotExist: return AnonymousUser() class TokenAuthMiddleware(BaseMiddleware): def __init__(self, inner): super().__init__(inner) async def __call__(self, scope, receive, send): try: token_key = (dict((x.split('=') for x in scope['query_string'].decode().split("&")))).get('token', None) except ValueError: print("error") token_key = None scope['user'] = AnonymousUser() if token_key is None else await get_user(token_key) return await super().__call__(scope, receive, send) TokenAuthMiddlewareStack = lambda inner: TokenAuthMiddleware(AuthMiddlewareStack(inner)) And here is the routing config: application = ProtocolTypeRouter( { "http": django_asgi_app, "websocket": TokenAuthMiddlewareStack( URLRouter( [ re_path(r"ws/chat/(?P<room_name>\w+)/$", consumers.ChatConsumer.as_asgi()) ] ) ) , } ) I debugged the receive_json method using breakpoints And I saw self.channel_name and self.channel_layer is None!! Does anyone … -
Does Django save model objects other than `save()` or `create()` methods?
I'm writing something like the following: class Foo(models.Model): a = models.CharField() def f(foo: Foo) -> Foo: y = Foo( **{field.name: getattr(foo, field.name) for field in foo._meta.get_fields()} ) # copy foo with pk y.a = "c" return y My concern is whether y are saved to DB before users call save() method. Could it occur? -
In Django's auth contrib module, how do I correctly return an error when overriding the asswordResetConfirmView view?
I'm using Django 3 and the auth contrib module. I want to override the reset password procedure via an API and so I have a method that looks like this .... class CompleteResetPasswordView(PasswordResetConfirmView): @method_decorator(csrf_exempt) def dispatch(self, request): body = json.loads(request.body) self.data = body # validate user, password, and confirm password if user is not None: ... return Response('Success', status=HTTP_200_OK) ... return Response('Error', status=HTTP_500_INTERNAL_SERVER_ERROR) When the user cannot be validated and the "return Response('Error', status=HTTP_500_INTERNAL_SERVER_ERROR)" is invoked, this error is returned AssertionError at /password-reset-complete .accepted_renderer not set on Response I would liek a JSON response (in addition to the 500 status code) to be returned to the view, but haven't figured out how to manipulate what I have to make this happen. -
Django static url setting is not working in production
I have uploaded stsatic files to Cloudflare R2 with python manage.py collectstatic command, and checked files are there. Also, allowed public access for the R2 bucket. I have these in my settings.py file for static related: STATIC_HOST = env("STATIC_HOST") STATIC_URL = STATIC_HOST + "/static/" STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),) STATICFILES_STORAGE = ( "django.contrib.staticfiles.storage.StaticFilesStorage" if DEBUG else "myproject.backends.storages.StaticStorage" ) ...and this is my .env file: DEBUG=True AWS_ACCESS_KEY_ID=my_r2_access_key_id AWS_SECRET_ACCESS_KEY=my_r2_secret_access_key AWS_STORAGE_BUCKET_NAME=my_r2_bucket_name # Endpoint for uploads AWS_S3_ENDPOINT_URL=https://my_account_id.r2.cloudflarestorage.com # Public access url STATIC_HOST=https://pub-a1b2c3d4e5f6.r2.dev When I runserver with DEBUG=False and go to localhost:8000/admin it does not load CSS properly, and static file requests are all 4xx and not using provided STATIC_URL but AWS_S3_ENDPOINT_URL. When I runserver with DEBUG=True it loads static files properly from provided STATIC_URL setting. I want to load static files from R2 bucket in production / DEBUG=False and use local static files with DEBUG=True. Please help me what I am doing wrong? -
Filtering multicheckbox on datable
i have a problem with my code, i try to make a datable with multiple checkbox filter on Django environement. i have tried multiple code, but for now, i have this code, for each collumn there is a list and i can check or not the checkbox, but the filter is not applicated. any suggestion would be very welcome. here the code : <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <script src="https://code.jquery.com/jquery-3.5.1.js"></script> <script src="https://cdn.datatables.net/fixedheader/3.2.3/css/fixedHeader.dataTables.min.css"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> <style> .dropdown-menu { max-height: 200px; overflow-y: auto; } </style> </head> <body> <h1>Liste des matches</h1> <table id="table_id" class="display"> <thead> <tr> <th> <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownPAYSEQP" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> PAYSEQP </button> <div class="dropdown-menu" aria-labelledby="dropdownPAYSEQP"> {% for match in matches %} <div class="form-check"> <input class="form-check-input" type="checkbox" value="{{ match.PAYSEQP }}" id="{{ match.PAYSEQP }}"> <label class="form-check-label" for="{{payseqp}}"> {{ match.PAYSEQP }} </label> </div> {% endfor %} </div> </div> </th> <th> <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownJOUEURS" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> JOUEURS </button> <div class="dropdown-menu" aria-labelledby="dropdownJOUEURS"> {% for match in matches %} <div class="form-check"> <input class="form-check-input" type="checkbox" value="{{ match.JOUEURS }}" id="{{ match.JOUEURS }}"> <label class="form-check-label" for="{{joueur}}"> {{ match.JOUEURS }} </label> </div> {% endfor %} </div> </div> … -
Django's remove_stale_contenttypes command fails with DoesNotExist error
I recently tried to run remove_stale_contenttypes in a Django 3.1 app, after deleting some custom permissions. The first time it run it warned me that some entries would be deleted, and I went ahead and entered 'yes'. The command failed with a DoesNotExist error for one of the models, and after that I can't even see the warning, it fails right away, with the following output: Traceback (most recent call last): File "C:\Users\Yamil\Google Drive\Proyectos\monely\manage.py", line 22, in <module> main() File "C:\Users\Yamil\Google Drive\Proyectos\monely\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Yamil\anaconda3\envs\monely\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Yamil\anaconda3\envs\monely\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Yamil\anaconda3\envs\monely\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Yamil\anaconda3\envs\monely\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\Yamil\anaconda3\envs\monely\lib\site-packages\django\contrib\contenttypes\management\commands\remove_stale_contenttypes.py", line 55, in handle collector.collect([ct]) File "C:\Users\Yamil\anaconda3\envs\monely\lib\site-packages\django\db\models\deletion.py", line 295, in collect if sub_objs: File "C:\Users\Yamil\anaconda3\envs\monely\lib\site-packages\django\db\models\query.py", line 291, in __bool__ self._fetch_all() File "C:\Users\Yamil\anaconda3\envs\monely\lib\site-packages\django\db\models\query.py", line 1303, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\Yamil\anaconda3\envs\monely\lib\site-packages\polymorphic\query.py", line 64, in _polymorphic_iterator real_results = self.queryset._get_real_instances(base_result_objects) File "C:\Users\Yamil\anaconda3\envs\monely\lib\site-packages\polymorphic\query.py", line 387, in _get_real_instances if base_object.polymorphic_ctype_id == self_model_class_id: File "C:\Users\Yamil\anaconda3\envs\monely\lib\site-packages\django\db\models\query_utils.py", line 149, in __get__ instance.refresh_from_db(fields=[field_name]) File "C:\Users\Yamil\anaconda3\envs\monely\lib\site-packages\django\db\models\base.py", line 635, in refresh_from_db db_instance = db_instance_qs.get() File "C:\Users\Yamil\anaconda3\envs\monely\lib\site-packages\django\db\models\query.py", line 429, in get raise self.model.DoesNotExist( productos.models.DoesNotExist: Producto matching query does not exist. … -
Django MPTT, can't get parent_id for threaded comments reply
My Problems are as follows: Im relatively new to Django. so sorry for this mess. I've tried to implement threaded comments to my blog via MPTT. But when i pressing the 'Reply' Button django throws me a Type Error Normal parent comments working correctly When i just create a comment with via the admin site, i can create parent comments and child comments and they will be indented just as expected in the main Application too... my Database is mySQL. The Error: in _calculate_inter_tree_move_values space_target = target_right - 1 ~~~~~~~~~~~~~^~~ TypeError: unsupported operand type(s) for -: 'NoneType' and 'int' my models.py: from django.db import models from django.contrib.auth.models import User from django.urls import reverse from mptt.models import MPTTModel, TreeForeignKey STATUS = ( (0,"Draft"), (1,"Publish") ) class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE, related_name='blog_posts') updated_on = models.DateTimeField(auto_now=True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-created_on'] def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail',args=[self.slug]) class Comment(MPTTModel): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=False) parent=TreeForeignKey('self', null=True, blank=True, on_delete=models.CASCADE, related_name='children') class MPTTMeta: order_insertion_by = … -
Django Filter using Q Objects on two Models
I am working a Django Application where I want to search two Models Profile and Account using Q objects. From what I did, it is searching only one Model (Account) and any attempt to search any value from the other Model (Profile) triggers an error. See my Model Code: class Profile(models.Model): customer = models.OneToOneField(User, on_delete=models.CASCADE, null = True) surname = models.CharField(max_length=20, null=True) othernames = models.CharField(max_length=40, null=True) gender = models.CharField(max_length=6, choices=GENDER, blank=True, null=True) address = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=11, null=True) image = models.ImageField(default='avatar.jpg', blank=False, null=False, upload_to ='profile_images', ) def __str__(self): return f'{self.customer.username}-Profile' class Account(models.Model): customer = models.OneToOneField(User, on_delete=models.CASCADE, null=True) account_number = models.CharField(max_length=10, null=True) date = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return f' {self.customer} - Account No: {self.account_number}' Here is my form: class SearchCustomerForm(forms.Form): value = forms.CharField(label = 'Enter Name or Acct. Number', max_length=30) Here is my views def create_account(request): if searchForm.is_valid(): #Value of search form value = searchForm.cleaned_data['value'] #Filter Customer by Surname, Othernames , Account Number using Q Objects user_filter = Q(customer__profile__exact = value) | Q(account_number__exact = value) #Apply the Customer Object Filter list_customers = Account.objects.filter(user_filter) else: list_customers = Account.objects.order_by('-date')[:8] Someone should help on how best to search using Q objects on two Models. -
How to fix search function in Django?
I have a page with the list of objects. I need a search function, but there is an error. I am in process of studying and I used from . import views and the search function worked, but then I replaced it to from .views import HomeView and modified some code. The list is shown, but as for search there is an error: type object 'HomeView' has no attribute 'Search' Urls.py: from django.urls import path #from . import views from .views import HomeView urlpatterns = [ #path('', views.home, name="home"), path('search/', HomeView.Search.as_view(), name='search'), path('', HomeView.as_view(), name="home"), ] Home.html: <div> <h3>Find</h3> <form action="{% url 'search' %}" method="get"> <input type="search" name="q" class="form-control" required=""> <button type="submit">Find!</button> </form> </div> <h3>Applications</h3> {% for application in object_list %} <div> <p>{{ application.name }}</p> </div> {% endfor %} </div> Views.py: from django.shortcuts import render from django.views.generic import ListView from .models import Application from .forms import ApplicationForm from django.urls import reverse_lazy class HomeView(ListView): model = Application template_name = 'home.html' #ordering = ['status'] class Search(ListView): def get_queryset(self): return Application.objects.filter(title__icontains=self.request.GET.get("q")) def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context["q"] = self.request.GET.get("q") return context </div> -
CKEDITOR PillowBackend Django disable thumbnail creation
By default, when inserting an image from the clipboard into the CKEDITOR editor, the images are saved in PNG format and take up a lot of disk space. I have enabled PillowBackend to be able to save images in JPG format, but its thumbnail is created along with the image, how can I disable thumbnail creation? Or maybe there is a way when inserting an image from the clipboard into the CKEDITOR editor, you can save the image in JPG format without enabling PillowBackend, so that there is no thumbnail creation? -
Creating a team of users with jobs
I want to make a model where users can create a team of users, and in these teams add the job that they did and choose recipient of the job(that is the member of this team) that they did it for. I don't how to create a choice field for the recipient of the job. from django.db import models from django.contrib.auth.models import User class Team(models.Model): name = models.CharField(max_length=120) members = models.ManyToManyField(User) class Job(models.Model): belonging = models.ForeignKey(Team,on_delete=models.CASCADE) executor = models.ForeignKey(User,on_delete=models.CASCADE) task_description = models.CharField(max_length=180) recipient = models.ManyToManyField(Team.members) # <-- -
django - only call <a href="{% url 'view'%}"> when clicked
In my web page i have a for loop that displays multiple <a> tags. When one of the <a> tags is clicked the user will be redirected to another url. My problem is that all of the href="{% url 'search' theme_path %}{{theme}}" gets called despite not being clicked and causes my page site to crash since the sub_themes list is quite large. I tried using forms as they should only call the {% url 'view' %} when clicked. But this got a bit fiddly. There must be some simple javascript code that can resolve my issue How can i only have the url be called when clicked? html <section id="all-themes-container"> {% for theme in sub_themes %} <div class="theme-container"> <a href="{% url 'search' theme_path %}{{theme}}">{{theme}}</a> </div> {% endfor %} </section> -
Django form request is always response with "GET" instead of "POST" even when I use <form action="" method="post">
Please help me m looking since hours for the solution but i didnt find something. Here is my HTML: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <style> input { width: 10%; margin: 0 auto; display: block; margin-left: auto; margin-right: auto; } </style> </head> <body> {% load crispy_forms_tags %} <div class="container"> <form action="" method="post"> {% csrf_token %} {% crispy form %} <input type="submit" class="btn btn-primary mx-auto d-block"> </form> </div> </body> </html> and here is my views.py: from django.shortcuts import render from .forms import UserInformationForm # Create your views here. def register(request): form = UserInformationForm() context = {"form": form} print(form) if request.method == "POST": print("Post") form = UserInformationForm(request.POST) if form.is_valid(): form.save() print(form) return render(request, 'index.html', context) The only response i get is: "GET /register/ HTTP/1.1" 200 3542 I already tried things like if request.method == "GET": But then I had on every field in my form a mark with "This fiel is required" -
I am using Django to create and update an Text area I want to save my updated textarea after clicking Insert
I am using Django to create and update an Text area. After putting a text that have variables between {}, I want to change them using button variable. So when I click on variable it will show me all the varaibles between {}, Si I can assign them a value. After I am done, I save my updated Text area after clicking Insert. The problem is when I click Insert, and I open my database, it shows me NULL for my text. I tried to print the variable text in the view, but I have None. Here is my model: class InputText(AbstractModule): text = models.TextField(default='', null=True, blank=True) def __str__(self): return self.text Here is my view: def save_variables_text(request): if request.method == 'POST': print(request.method) text = request.POST.get('input-text') print(text) InputText.objects.create(text=text, user=request.user) return render(request, 'modules/gabarits/previsualise.html') Here is my previsualise.html file: <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="modal-dialog modal-md"> </form> <div class="modal-content" hx-target="this" hx-swap="outerHTML" id="this"> {% load crispy_forms_tags %} <!-- Modal Header --> <div class="modal-header"> <h4 class="modal-title">Show gabarit</h4> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <!-- Modal body --> <div class="modal-body"> <pre style="font-size: 12px"><textarea id='input-text' name='input-text' style='height:100px; width: 800px;'>{{commande}}</textarea></pre> {% if formset %} <button class="mb-2 btn btn-outline-secondary mr-2" id="variables-button" type="button" onclick="openModal()">Variables</button> {% endif %} <div id="modal" … -
docker nginx django gunicorn 502 bad gateway
i am a beginner in the docker I want deploy my django project on hostinger.com vps so I am using docker nginx and gunicorn for this I dockrized my django project a test it on the localhost every thing is good and my project is working by when i deploy it on the vps it show me 502 Bad gateway i don't have any idea ? docker-compoe.yml version: "3.7" services: app: build: './app' container_name: 'app' restart: 'always' expose: - '8000' # ports: # - "8000:8000" environment: - "MARIADB_DATABASE=django_app" - "MARIADB_USER=peshgaman" - "MARIADB_PASSWORD=m_nasir5555" - "MARIADB_HOST=mariadb" volumes: - type: 'bind' source: './volumes/app' target: '/app' depends_on: - "mariadb" - "nginx" mariadb: image: 'mariadb:latest' container_name: 'mariadb' restart: 'always' expose: - '3306' # ports: # - "8000:8000" environment: - "MARIADB_DATABASE=django_app" - "MARIADB_USER=peshgaman" - "MARIADB_PASSWORD=m_nasir5555" - "MARIADB_ROOT_PASSWORD=m_nasir5555" volumes: - type: 'bind' source: './volumes/dbdata' target: '/var/lib/mysql' nginx: build: './nginx' container_name: 'nginx' restart: 'always' ports: - "80:80" volumes: - type: 'bind' source: './volumes/media' target: '/app/media' - type: 'bind' source: './volumes/static' target: '/app/static' app Dockerfile FROM python:alpine ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 ENV DJANGO_SUPERUSER_PASSWORD=admin RUN mkdir /app COPY requirements.txt /app WORKDIR /app RUN apk update RUN apk add --no-cache gcc python3-dev musl-dev mariadb-dev RUN pip install --upgrade pip …