Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get First and Last Related Object for Django Rest API
I have Django Rest API serializers based on 2 models, Book and Chapter In the Book serializer I want 2 custom fields first_chapter last_chapter Each having objects of model Chapter as you can understand from the field name first and last objects order by published_at field I tried something like below to get the last chapter class LastChapterField(serializers.RelatedField): def get_queryset(self): return core_models.Chapter.objects\ .filter(comic=M.OuterRef("pk"))\ .select_related("number")\ .order_by("-published_at")[:1] But I don't see the last chapter included in my results even though it is explicitly mentioned in fields of Book Serializer I want the complete object in returning result and I want to be able to use order by on one of these nested fields (first_chapter or last_chapter) of Chapter model object. -
Hey is it possible to call one serializer class insider another in drf? Without having any foreign key relationship
class AuthorSerializer(ModelSerializer): class Meta: model = Author fields = "__all__" class BookSerializer(ModelSerializer): class Meta: model = Book fields = "__all__" I want to get data of AuthorSerializer in BookSerializer. Is it Possible? -
CKEditor doesn't save data
I'm using CKEditor for a form. In the admin it works fine, but when using it in the ModelForm of a CreateView the editor doesn't save data. As in the official docs, with this code: class EventForm(forms.ModelForm): description = forms.CharField(widget=CKEditorWidget()) image = forms.ImageField(widget=forms.ClearableFileInput(), required=False) class Meta: model = Event fields = ['title', 'description', 'type', 'start_date', 'end_date', 'fee'] And this html: <div> <form hx-post="{{ request.path }}" enctype="multipart/form-data" class="modal-content"> {% csrf_token %} <div class="modal-header"> <h1>Create new event</h1> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> {{form.media}} {{form.as_p}} </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button> <input type="submit" value="Submit"> </div> </form> </div> It won't let me submit the form as it will keep saying that the description field is required. Trying to add the CKEditor widget field in the init method, with this code: class EventForm(forms.ModelForm): image = forms.ImageField(widget=forms.ClearableFileInput(), required=False) class Meta: model = Event fields = ['title', 'description', 'type', 'start_date', 'end_date', 'fee'] def __init__(self, *args, **kwargs): super(EventForm, self).__init__(*args, **kwargs) self.fields['start_date'].widget = forms.SelectDateWidget() self.fields['end_date'].widget = forms.SelectDateWidget() self.fields['description'].widget = CKEditorWidget() The form will be sent, and the instance created. However, the 'description' field will be empty even if I enter some content. This is my view: class CreateEvent(LoginRequiredMixin, CreateView): model = Event form_class = … -
Page not found (404) upon Heroku Deployment
I have been having difficulties getting to deploy my Heroku app with my Django and React app. The error is as follows: Page not found (404) Request Method: GET Request URL: https://true-friends-404.herokuapp.com/login/ Using the URLconf defined in truefriends.urls, Django tried these URL patterns, in this order: admin/ ^authors/$ [name='authors-list'] ^authors\.(?P<format>[a-z0-9]+)/?$ [name='authors-list'] ^authors/(?P<pk>[^/.]+)/$ [name='authors-detail'] ^authors/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='authors-detail'] ^$ [name='api-root'] ^\.(?P<format>[a-z0-9]+)/?$ [name='api-root'] ^posts/$ [name='posts-list'] ^posts\.(?P<format>[a-z0-9]+)/?$ [name='posts-list'] ^posts/(?P<pk>[^/.]+)/$ [name='posts-detail'] ^posts/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='posts-detail'] ^$ [name='api-root'] ^\.(?P<format>[a-z0-9]+)/?$ [name='api-root'] swagger/ [name='schema-swagger-ui'] api/ api/auth/ friendrequest/ [name='friend_request_list'] friendrequest/accept/<int:fr_id>/ [name='friend_request_accept'] friendrequest/reject/<int:fr_id>/ [name='friend_request_reject'] friendrequest/<int:author_id>/ [name='friend_request_to_user'] authors/<int:author_id>/ authors/<int:author_id>/ posts/<int:post_id>/ comments/<int:comment_id>/ authors/<int:author_id>/inbox/ followers/ [name='followers_list'] following/ [name='following_list'] unfollow/<int:user_id>/ [name='unfollow_by_user_id'] unfriend/<int:user_id>/ [name='unfriend_by_user_id'] withdraw/<int:user_id>/ [name='withdraw_by_user_id'] truefriends/ [name='true_friends_list'] posts/<int:post_id>/ authors/<int:author_id>/ currentauthor/ ^media/(?P<path>.*)$ The current path, login/, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. Here is the urls.py file # import ... post_router = routers.DefaultRouter() post_router.register(r'posts', PostView, 'posts') logged_in_post_router = routers.DefaultRouter() logged_in_post_router.register(r'posts', LoggedInPostView, 'my-posts') author_router = routers.DefaultRouter() author_router.register(r'authors', AuthorView, 'authors') post_like_router = routers.DefaultRouter() post_like_router.register(r'likes', PostLikeView, 'post-likes') author_like_router = routers.DefaultRouter() author_like_router.register(r'likes', AuthorLikeView, 'author-likes') post_comment_router = routers.DefaultRouter() post_comment_router.register(r'comments', PostCommentView, 'post-comments') author_comment_router = routers.DefaultRouter() author_comment_router.register(r'comments', AuthorCommentView, 'author-comments') schema_view = get_schema_view( openapi.Info( # add your swagger doc title … -
Why my conditional statement does not return true?
I'm getting input from html <form class="form" action="{% url 'search' %}" method="POST"> {% csrf_token %} <input type="text" name="input" id="input" style="height: 40px" /> <button type="submit" style="height: 40px; width: 110px; margin-left: 40px" > Filter post </button> and in the views.py def search(request): ... if request.method=='POST': input=int(request.POST.get('input')) # print(type(input)) for field in posts_data: if (input == field['id']): print(field['id']) output['post'] = field return render(request, 'post.html', {'post':output}) else: return render(request, 'post.html', {'posts': posts_data}) so I printed in terminal input got same as I entered and also the type is confirmed integer. I also did print field['id'] and got range of numbers( including same number as I input) so what possibly be the problem? -
ImportError: cannot import name 'Celery' from partially initialized module 'celery' (most likely due to a circular import)
With latest version of celery, in python 3.10.6, I am getting the above error, trace back is as follows. Traceback (most recent call last): File "/usr/lib/python3.10/threading.py", line 1016, in _bootstrap_inner self.run() File "/usr/lib/python3.10/threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "/home/biju/Desktop/trial/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/biju/Desktop/trial/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/home/biju/Desktop/trial/lib/python3.10/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/home/biju/Desktop/trial/lib/python3.10/site-packages/django/core/management/__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "/home/biju/Desktop/trial/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/biju/Desktop/trial/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/biju/Desktop/trial/lib/python3.10/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/biju/Desktop/trial/lib/python3.10/site-packages/django/apps/config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.10/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 "/home/biju/Desktop/trial/lib/python3.10/site-packages/django_celery_beat/models.py", line 10, in <module> from celery import current_app, schedules File "/home/biju/Desktop/trial/celery.py", line 3, in <module> from celery import Celery ImportError: cannot import name 'Celery' from partially initialized module 'celery' (most likely due to a circular import) tried to installing importlib-metadata==4.13.0, but error persists, Django version is … -
login wrong show the messages error but not show out
login wrong username the messages error no show out here is code python def loginPage(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') try: user = User.objects.get(username=username) except: messages.error(request, 'User does not exist') context = {} return render(request, 'base/login_register.html', context) here is html code {% if messages %} <ul class="messages"> {% for message in messages %} <li>{{ message }}</li> {% endfor %} </ul> {% endif %} -
How to pass URL parameters and get the values with GET request method in Django rest framework
I want to pass url parameters in this format http://localhost:8000/api/projects/?id=2021&a=2&b=3&c=4 and get the values in view function -
Where should I put my sqlalchmey engine/connection object in django?
I have already created a lot of models and query methods by sqlalchemy and now I want to build a website on it to provide services. The problem is I am not sure where to put my engine in django code structure: engine = create_engine("postgresql+psycopg2://scott:tiger@localhost:5432/mydatabase") -
AttributeError: 'NoneType' object has no attribute 'is_nightly'
I've got an error on the expression with below defined function on serializer.py and i have an ordering items with different calculation with posting on nightly basis and once posting. if special_order_item.special_item.is_nightly == True: AttributeError: 'NoneType' object has no attribute 'is_nightly' the error was referred to "if special_order_item.special_item.is_nightly == True:" models.py class SpecialsItem(models.Model): hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE, related_name="special_items", null=False, blank=False) code = UpperCaseCharField(max_length=50, blank=True, null=True) desc = models.CharField(max_length=100, blank=True, null=True) pms_tran_code = UpperCaseCharField(max_length=50, blank=True, null=True) unit_price = models.DecimalField(max_digits=20, decimal_places=10, default=0) is_nightly = models.BooleanField(default=True) inventory = models.IntegerField(default=0) image = models.ImageField(upload_to='img', blank=True, null=True, default='') serializers.py class SpecialsOrderItemsSerializer(serializers.ModelSerializer): special_item = SpecialItemSerializer(many=False, read_only=True) amount = serializers.SerializerMethodField(method_name='sub_total') class Meta: model = SpecialOrderItems fields = [ 'id', 'reservation', 'special_item', 'qty', 'amount', 'created_by', 'updated_by' ] def sub_total(self, special_order_item:SpecialOrderItems): # definedname : model_object if special_order_item.special_item.is_nightly == True: items_total = special_order_item.qty * special_order_item.special_item.unit_price * special_order_item.reservation.night return items_total else: items_total = special_order_item.qty * special_order_item.special_item.unit_price return items_total Looking a expertise for who have experiencing to figure out a solution -
Is it possible somehow without refreshing the pages on Django to send a request via SSH to a virtual machine running Ubuntu?
Good afternoon, I have a frequently asked question, for example, <button>Check</button> Is it possible somehow without refreshing the page to send a request via SSH to a virtual machine running Ubuntu? For example: The csgo server is on a permanent machine, it has possible options: IP: 192.168.44.122/94.32.143.84 PORT for SSH: 44 USER NAME: test PASSWORD: test Django is on local machine 127.0.0.1:8000 or localhost:8000. The csgo server is started with "./csgoserver start". Is it possible somehow to send a request with "./csgoserver start" to the local machine, on the click of a button on the page, to start the server? I searched for information and did not find it. With the help of ajax, if I understand correctly, it is possible to send a request only if there are servers on the same machine, right? I would be grateful for the answer where should I look, what to study, so that I can implement this idea. One guy suggested that you can look towards REST, but I can't figure out how to implement what I need through REST. -
Why I cannot connect my order error page to my Django website?
I'm trying to build an ecommerce site, but I don't understand how you can connect the order error page to the website. I've tried adding a window.location.replace to the JavaScript file after the .then function in the result.error section. }).then(function(result) { if (result.error) { console.log('payment error') console.log(result.error.message); window.location.replace("http://127.0.0.1:8000/payment/error/"); } else { if (result.paymentIntent.status === 'succeeded') { console.log('payment processed') window.location.replace("http://127.0.0.1:8000/payment/orderplaced/"); } } }); }, error: function (xhr, errmsg, err) {}, I've also tried adding an if else function beneath the succeeded. }).then(function(result) { if (result.error) { console.log('payment error') console.log(result.error.message); } else { if (result.paymentIntent.status === 'succeeded') { console.log('payment processed') window.location.replace("http://127.0.0.1:8000/payment/orderplaced/"); } else { if (result.paymentIntent.status === 'failed') { console.log('payment error') window.location.replace("http://127.0.0.1:8000/payment/error"); } } } }); }, error: function (xhr, errmsg, err) {}, I've tried editing the Error class to a define, but it didn't work out within the payment views.py. I've tried creating a new define called error and made the orders urls.py connect to the new error defined, but nothing happened when I try to put a declined credit card information. My payment views.py: @csrf_exempt def stripe_webhook(request): payload = request.body event = None try: event = stripe.Event.construct_from( json.loads(payload), stripe.api_key ) except ValueError as e: print(e) return HttpResponse(status=400) if event.type == … -
How to get raw value of the QuerySet
I'm trying to return the raw value "Alberto Santos", but in my HTML, the function returns a array. <QuerySet [<Funcionarios: Alberto Santos>]> My function "funcionarios_nome" class ListaFuncionariosView(ListView): model = Funcionarios template_name = '../templates/funcionarios/lista_funcionarios.html' paginate_by = 10 ordering = ['FuncionarioCartao'] queryset = Funcionarios.objects.filter(EmpresaCodigo=1) def funcionarios_nome(self): funcionarios = Funcionarios.objects.filter(FuncionarioNome='Alberto Santos') return funcionarios MY HTML <p>{{ view.funcionarios_nome }}</p> I Tried to use .values() function, but i'dont know how to use -
In Haystack logical operators give unexpected results
How to use logical operators in the solr + haystack bundle? At the moment, the search in my system is done something like this: I get the field from the post data I give them to the filter(text=post[query]) function It doesn't work, I tried additionally giving it to the Auto Query function, which also didn't work. request example "covid OR coronavirus” I tried additionally giving it to the Auto Query function, which also didn't work. request example "covid OR coronavirus” -
Celery not working on EC2 instance in production
i've been trying to deploy a django appllication on aws ec2, i've been successfull at deploying it so far except getting celery to work,i tried testing the celery worker by trying to run it on the shell temporarily with this command: celery -A ReelShopBackend worker -l INFO which works in locally and also in docker but when i run it on the ec2 instance it gives this error: Traceback (most recent call last): File "/home/ubuntu/Renv/bin/celery", line 8, in <module> sys.exit(main()) File "/home/ubuntu/Renv/lib/python3.10/site-packages/celery/__main__.py", line 15, in main sys.exit(_main()) File "/home/ubuntu/Renv/lib/python3.10/site-packages/celery/bin/celery.py", line 217, in main return celery(auto_envvar_prefix="CELERY") File "/home/ubuntu/Renv/lib/python3.10/site-packages/click/core.py", line 1130, in __call__ return self.main(*args, **kwargs) File "/home/ubuntu/Renv/lib/python3.10/site-packages/click/core.py", line 1055, in main rv = self.invoke(ctx) File "/home/ubuntu/Renv/lib/python3.10/site-packages/click/core.py", line 1657, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/home/ubuntu/Renv/lib/python3.10/site-packages/click/core.py", line 1404, in invoke return ctx.invoke(self.callback, **ctx.params) File "/home/ubuntu/Renv/lib/python3.10/site-packages/click/core.py", line 760, in invoke return __callback(*args, **kwargs) File "/home/ubuntu/Renv/lib/python3.10/site-packages/click/decorators.py", line 26, in new_func return f(get_current_context(), *args, **kwargs) File "/home/ubuntu/Renv/lib/python3.10/site-packages/celery/bin/base.py", line 134, in caller return f(ctx, *args, **kwargs) File "/home/ubuntu/Renv/lib/python3.10/site-packages/celery/bin/worker.py", line 343, in worker worker = app.Worker( File "/home/ubuntu/Renv/lib/python3.10/site-packages/celery/worker/worker.py", line 99, in __init__ self.setup_instance(**self.prepare_args(**kwargs)) File "/home/ubuntu/Renv/lib/python3.10/site-packages/celery/worker/worker.py", line 120, in setup_instance self._conninfo = self.app.connection_for_read() File "/home/ubuntu/Renv/lib/python3.10/site-packages/celery/app/base.py", line 808, in connection_for_read return self._connection(url or self.conf.broker_read_url, **kwargs) File "/home/ubuntu/Renv/lib/python3.10/site-packages/celery/app/base.py", line 867, in … -
Can I get auto-generated signin forms in dj-rest-auth, instead of manually writing an html form?
I'm adding dj-rest-auth to my django application. It's a traditional Django app rather than an SPA -- no react etc. I looked to the demo app hoping to basically use those patterns. However, I'm disappointed to see that the templates have hard-coded forms, for example https://github.com/iMerica/dj-rest-auth/blob/master/demo/templates/fragments/signup_form.html . These forms should be obtainable from django rest framework serializers, right? For example in my own app, with no custom templates, if I go to http://127.0.0.1:8000/dj-rest-auth/registration/ I get an autogenerated API form: Is it possible to build my signin view form from that drf serializer? Maybe there's already a view I can use? Basically I want to take this API endpoint and make it work for GET... Update: Update: I'm able to generate the form by getting RegisterSerializer from from dj_rest_auth.registration.app_settings, adding it to template context, and rendering it using {% render_form RegisterSerializer %}, so I think I'm on the right track. -
How to run django manage.py commands when using docker compose to avoid issues with permissions
I have created a Django, Docker, Postgres project, based on the example on Docker's Github. On my Linux machine I have 2 Docker containers, one for Django and one for Postgres. When I run manage.py commands using docker compose, such as docker compose run web django-admin startapp auth, the directory and files created are owned by root. This means I need to change the ownership each time I do this. I use sudo chown -R. If I don't change ownership, when I try to edit a file generated by manage.py, I get an error message saying I have insufficient privileges and that I need to retry as superuser. When I try to run this command without docker compose, e.g. python3 manage.py startapp auth, I get ModuleNotFoundError: No module named django. Did you forget to activate a virtual environment? Is it possible for the output of the manage.py commands to be owned by me? I know that the docker process is owned by root... -
DRF display verbose message in error message for a custom exception handler
Here is my custom exception handler: def my_exception_handler(exc, context): response = exception_handler(exc, context) if response is not None: error_code = 'unknown' if hasattr(exc, 'default_code') : error_code = exc.default_code message = '' if hasattr(exc, 'default_detail'): message = exc.default_detail error = { "error":response.data, "code":error_code, 'message':message, } response.data = error return response The problem here is whenever I send bad data I get a response like this: { "error": { "email": [ "Enter a valid email address." ], "phone_number": [ "asd is not a valid phone" ] }, "code": "invalid", "message": "Invalid input." } As you can see the message is just "Invalid input." But I want to get a verbose message here. Any idea about it? -
Is there a way to load avatar of each user using static method in Django?
I'm looping through each message which has a particular user which in intern as an image associated with it. <img src="{{message.user.avatar.url}}" /> I want to convert it something like this (which I know is obviously very wrong) <img src="{% static {{message.user.avatar.url}} %}" /> Is there a way to do so where I can find the equivalent working command of the above code? -
Trying to dockerize Django app, Docker cannot find ft2build.h
I'm new to Docker and I'm trying to dockerize a Django app: FROM python:3.10.8-alpine3.15 ENV PYTHONUNBUFFERED=1 WORKDIR /app RUN apk update \&& apk add --no-cache gcc musl-dev postgresql-dev python3-dev libffi-dev \&& pip install --upgrade pip COPY ./requirements.txt ./ RUN pip install -r requirements.txt COPY ./ ./ CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] But when I run docker build -t sometag . I receive the following error: #9 23.05 Preparing metadata (setup.py): started #9 23.32 Preparing metadata (setup.py): finished with status 'error' #9 23.33 error: subprocess-exited-with-error #9 23.33 #9 23.33 × python setup.py egg_info did not run successfully. #9 23.33 │ exit code: 1 #9 23.33 ╰─> [10 lines of output] #9 23.33 ##### setup-python-3.10.8-linux-x86_64: ================================================ #9 23.33 ##### setup-python-3.10.8-linux-x86_64: Attempting build of _rl_accel #9 23.33 ##### setup-python-3.10.8-linux-x86_64: extensions from 'src/rl_addons/rl_accel' #9 23.33 ##### setup-python-3.10.8-linux-x86_64: ================================================ #9 23.33 ##### setup-python-3.10.8-linux-x86_64: =================================================== #9 23.33 ##### setup-python-3.10.8-linux-x86_64: Attempting build of _renderPM #9 23.33 ##### setup-python-3.10.8-linux-x86_64: extensions from 'src/rl_addons/renderPM' #9 23.33 ##### setup-python-3.10.8-linux-x86_64: =================================================== #9 23.33 ##### setup-python-3.10.8-linux-x86_64: will use package libart 2.3.21 #9 23.33 !!!!! cannot find ft2build.h #9 23.33 [end of output] #9 23.33 #9 23.33 note: This error originates from a subprocess, and is likely not a problem with pip. #9 23.33 … -
How to Run an ML model with Django on Live server
I have a Django project that uses a public ML model("deepset/roberta-base-squad2") to make some predictions. The server receives a request with parameters which trigger a queued function. This function is what makes the predictions. But this works only on my local. Once I push my project to a live server, the model no starts to run but never completes. I have tried to set up the project using different guides, to avoid my project downloading the ML model every time a request is made, but it doesn't solve it. I don't know what else to do, please. If there's any extra information needed, I can provide. Here is my setup as it is now: views.py class BotView(GenericAPIView): serializer_class = BotSerializer def post(self, request, *args, **kwargs): try: serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() print(serializer.data) return Response(data=serializer.data, status=status.HTTP_200_OK) except Exception as e: print(str(e)) return Response(data=str(e), status=status.HTTP_400_BAD_REQUEST) serializers.py from .tasks import upload_to_ai class BotSerializer(serializers.Serializer): questions = serializers.ListField(required=True, write_only=True) user_info = serializers.CharField(required=True, write_only=True) merchant = serializers.CharField(required=True, write_only=True) user_id = serializers.IntegerField(required=True, write_only=True) def create(self, validated_data): # call ai and run async upload_to_ai.delay(validated_data['questions'], validated_data['user_info'], validated_data['merchant'], validated_data['user_id']) return "successful" tasks.py from bot.apps import BotConfig from model.QA_Model import predict @shared_task() def upload_to_ai(questions:list, user_info:str, merchant:str, user_id:int): model_predictions = predict(questions, BotConfig.MODEL, … -
Best implementation for working hours of multiple users in week in Django
I would like to understand the best implementation to manage the working hours of a user which could also be divided into different time slots. example: from 8:00 to 12:00 and from 15:00 to 18. For now I was proceeding like this: class WorkHoursDay(models.Model): weekday = models.CharField(choices=WEEKDAYS, max_length=255) from_hour = models.TimeField(choices=TIME) to_hour = models.TimeField(choices=TIME) barber = models.ForeignKey(Barber, on_delete=models.CASCADE) class Meta: ordering = ('weekday', 'from_hour') unique_together = (('weekday', 'barber'),('from_hour', 'to_hour')) The TIME list is developed like this: [8:00, 8:05, 8:10...]. In this way I'm going to manage the users' working hours day by day by generating an object for each day and I don't know how good it is. Sounds like dirty programming to me. -
Redirection to previous page after login using LoginRequiredMiddleware
I used to use next_param = request.POST.get('next') to redirect users to their previous page after they log in. I however, decided to go fancier with my code and now force any unauthenticated user to login by using LoginRequiredMiddleware: users are automatically redirected to login page if not authenticated. This allows me to avoid having to call a decorator for all views. Instead, specify the accessible views that don't require the user to be logged in. Small problem: my next_param = request.POST.get('next')doesnt work now for obvious reason: I cannot stick ?next={{ request.path|urlencode}} in the referring page since the redirection happens automatically and the user doesnt have to click anywhere. What alternative do I have to redirect the user to the initial/previous page they landed on before being redirected automatically? base.py MIDDLEWARE = [ .. 'mysite.middleware.LoginRequiredMiddleware', ] middleware.py import re from django.conf import settings from django.shortcuts import redirect EXEMPT_URLS = [re.compile(settings.LOGIN_URL.lstrip('/'))] if hasattr(settings, 'LOGIN_EXEMPT_URLS'): EXEMPT_URLS += [re.compile(url) for url in settings.LOGIN_EXEMPT_URLS] class LoginRequiredMiddleware: pass def __init__(self, get_response): self.get_response = get_response def __call__ (self, request): response = self.get_response(request) return response def process_view(self, request, view_func, view_args, view_kwargs): assert hasattr(request,'user') path = request.path_info.lstrip('/') print(path) if not request.user.is_authenticated: if not any(url.match(path) for url in EXEMPT_URLS): return … -
how to upload pdf file and excel sheet in one submit?
I have a django application and I try to upload a pdf file and a excel file with one submit function. So The pdf function works. But If I try to upload a excel sheet then I get this error: 'utf-8' codec can't decode byte 0xa0 in position 16: invalid start byte But I tested the excel function seperately and that works. But apperently combing with the pdf function it doesn't work. So this is the template: {% extends 'base.html' %} {% load static %} {% block content %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Create a Profile</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="{% static 'main/css/custom-style.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'main/css/bootstrap.css' %}" /> </head> <body> <div class="container center"> <span class="form-inline" role="form"> <div class="inline-div"> <form class="form-inline" action="/controlepunt140" method="POST" enctype="multipart/form-data"> <div class="d-grid gap-3"> <div class="form-group"> {% csrf_token %} {{ pdf_form }} </div> <div class="form-outline"> <div class="form-group"> <textarea class="inline-txtarea form-control" id="content" cols="70" rows="25"> {{content}}</textarea> </div> </div> </div> <div class="d-grid gap-3"> <div class="form-group"> {{ excel_form }} </div> <div class="form-outline"> <div class="form-group"> <textarea class="inline-txtarea form-control" id="content" cols="70" rows="25"> {{conten_excel}}</textarea> </div> </div> </div> <button type="submit" name="form_pdf" class="btn btn-warning">Upload!</button> </form> </div> </span> </div> </body> </html> {% endblock … -
Need to be superuser to edit a file of a django app. The django project has a Docker Container
I have cloned, followed the instructions, and setup the Docker, Django, Postgres project from Docker's Github on my Linux machine. I used docker compose run web django-admin startapp auth to setup the app's directory. When I edit a file in auth, e.g. auth/models.py, I get an insufficient permissions error message. auth/ is owned by root, which is confusing because manage.py is owned by me. I ran sudo chown -R $USER:$USER composeexample manage.py as instructed by the ReadMe. I don't want to have to chown each new app I make.