Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
mysql: how to resolve duplicate key errot
My django project has a migration that creates a foreign key on a table. When the migrate command is executed, I receive a stacktrace with error : MySQLdb._exceptions.OperationalError: (1061, "Duplicate key name "..." I located the key in table_constraints and in table_constraints_extensions. It doesn't appear to be in any other constraint table. There is one instance of the same key in each table. The foreign key was created, and actually works, but the migration fails to complete due to duplicate keys. I'm just not sure exactly where the duplication is because the FK constraint appears once in each of the tables mentioned above. My project can function without doing anything further, but the migration process will be broken until I fix this in the db. How and where do I fix this problem? delete from table_constratins ... alter table projects_project drop constraint ... -
CSS making boxes too big and taking up all the required space
I'm using Django's HTML scripting to iterate through a list of tags from a ManyToManyField for an article. Getting the information works, but the actual sizing of the borders around the tags ends up being all wrong. The boxes are absurdly big. The titles also aren't where I want them to be, though that is on hold. The CSS is a combination of custom CSS and Tailwind (yes I know that's a bad practice, but I'm lazy). HTML: {% extends 'head.html' %} {% load static %} {% block content %} <h1 class="flex items-center justify-center text-6xl">Articles</h1> <br> {% if articles %} <div class="flex items-center justify-center"> <div class="posts"> {% for article in articles %} <a href="{{ article.get_absolute_url }}"> <div class="article_box"> <span>{{ article.article_title }}</span> <div> {% for tag in article.article_tags.all %} <div class="tag">{{tag}}</div> {% endfor %} </div> </div> </a> {% endfor %} </div> </div> {% endif %} {% endblock %} CSS: .posts { font-size: 20px; display: grid; gap: 4rem; grid-template-columns: repeat(3, minmax(0, 1fr)); padding-left: 12rem; padding-right: 12rem; } .posts div { aspect-ratio: 1; } .article_box { width: 3/12; border: 2px solid black; padding: 0.5rem; } .tag { border: 2px solid black; border-radius: 20%; padding: 0.25rem; margin: 0.15rem; } .tags { display: flex; flex-basis: … -
Is there a way to identify when a 'like' was put on a blog post?
I've got a standard blog post set up where users can like posts. I'd like to be able to work out which posts have had the most likes in a given time frame but I'm not sure how to identify when a like was attributed to a post. My Post model: class Post(models.Model): objects = PostManager() author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, default=None, null=True) title = models.CharField(max_length=100) description = models.TextField(max_length=500) date = models.DateTimeField(auto_now_add=True) likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="post_like", blank=True) Other posts I've seen with a similar question have a Like model, is there a way I can do what I want using my current model or do I need to create a separate model for it? I was hoping to do something like adding auto_now_add=True to my likes attribute, similar to what I've done with date, but I know that only tells me when a blog post object was created. -
django celery tasks are executed before establishing a websocket connection
The user uploads the file to the form, after which the form with the file is sent to the server, and upon successful validation, I perform the following actions: def form_valid(self, form): storage = FileSystemStorage() file_path = storage.save(form.cleaned_data['file'].name, form.cleaned_data['file']) task = tasks.extract_text_from_pdf.delay(services.full_path(file_path)) return HttpResponseRedirect(reverse('pdf:download_result', kwargs={'task_id': task.id})) I temporarily save the file to the local file system and pass the file path to the celery task. After submitting the task to celeri, I redirect the user to another page where I establish a websocket connection to the server to be notified of the file processing result. In celery tasks, I open a file and perform the necessary actions with it, after which I send a message to the consumer. @shared_task def send_notification(message, task_id): channel_layer = get_channel_layer() room_group_name = f'download_result_{task_id}' async_to_sync(channel_layer.group_send)( room_group_name, { 'type': 'notification_message', 'message': message } ) @shared_task def extract_text_from_pdf(pdf_file_path): with open(pdf_file_path, 'rb') as file: reader = PdfReader(BytesIO(file.read())) text = "" for page in reader.pages: text += page.extract_text() + "\n" text = text.replace('\n', '\r\n') send_notification.delay(text, current_task.request.id) But I encountered a problem - celery tasks are executed faster than the websocket connection is established and as a result the message does not reach the client side. src.pdf_processing.tasks.extract_text_from_pdf[8f535575-803d-4679-8007-7a4404a372c1] succeeded in 0.148360932000287s: None … -
Resolving ImportError: Module "redis.connection" does not define a "HiredisParser" attribute/class
My django project has this issue after I updated my redis to version 5.4.0. It seems that the HiredisParser that I was using in my PARSER_CLASS in the redis configuration could not be found in this update. After taking a look at the change log, it seems the issue is a rename of the HiredisParser class from HiredisParser to _HiredisParser. So a simple change from this: "PARSER_CLASS": "redis.connection.HiredisParser" to this: "PARSER_CLASS": "redis.connection._HiredisParser" should fix the issue. Note that if hiredis package is already installed you can remove the whole line completely in your django cache configuration as it will by default select _HiredisParser if hiredis is installed. Relevant source: https://github.com/jazzband/django-redis/issues/676 -
How to change the value of a field in Django after a while?
I have a user model and I just added a premium field in it, now I want after expiration_date expired, the value of is_premium to change to False and, expiration_date and premium_time to change to none or something like that My user model: class User(AbstractUser): PREMIUM_TIME_CHOICES = ( (1, "1 Month"), (3, "3 Month"), (6, "6 Month"), (12, "12 Month") ) id = models.AutoField(primary_key=True) email = models.EmailField(unique=True) is_premium = models.BooleanField(default=False) expiration_date = models.DateTimeField(blank=True, null=True) premium_time = models.CharField(blank=True, null=True, choices=PREMIUM_TIME_CHOICES, max_length=1) My siganls: @receiver(post_save, sender=account_models.User) def add_premium_time(sender, instance, **kwargs): if instance.is_premium: expiration_date = timezone.now() + timezone.timedelta(days=(instance.premium_time * 30)) instance.expiration_date = expiration_date instance.save() -
Page not found (404)/Request Method: POST
Only the seller should be able to sell the item by clicking the button and no one else can offer a price after that. Also, the winner must be specified here and the winner can view their products by entering the product page and also viewing the winners page. The winners page is also in the layout format and from there we should be able to see the product specifications that are in win.html. But now, by clicking on the button, it shows the error that I wrote. Please tell me what to do to fix it. thanks:) Page not found (404) No List matches the given query. Request Method: POST Request URL: http://127.0.0.1:8000/off/ Raised by: auctions.views.off views.py: @login_required(login_url="login") def win(request, username): try: your_win = List.objects.filter(user = username) except: your_win = None return render(request, "auctions/win.html",{ "user_winlist" : your_win, }) @login_required(login_url="login") def off(request): product = request.GET.get('productid', False) users = Bid.objects.filter(user = request.user) if users == (List.user): product.is_closed = True product.save() return win(request, request.user.username) return product_detail(request,product) product_detail.html: <ul> {% for offer in offers %} <li>{{ offer.user.username }} offered ${{ offer.offered_price }}</li> {% if user.id == user.id %} <form method="post" action="{% url 'off' %}"> {% csrf_token %} <input type="hidden" name="product" value="{{ product }}"> … -
how to generate a list of endoints using a specific func
In my django app I want to keep track of all endpoints that use a particular function inside them. Let's call the function caching_func. I encapsulate my endpoints inside view classes, such as this: class TemplateViewSet(GenericViewSet): @action( detail=False, methods=["GET"], ) def download(self, request, *args, **kwargs): """ Returns a Zip file with all generated template files. """ # Create a HttpResponse with the contents to download response = zip_file_download() # cache response caching_func(response) return response @action( detail=False, methods=["POST"], ) def upload(self, request, *args, **kwargs): """ Accepts an uploaded file """ response = do_upload_work() return response def get_queryset(self): return None You can see that caching_func is invoked inside the download endpoint but not inside the upload endpoint. When the server is started, I want to construct a list of the endpoints that use caching_func, and I want the output to be the full endpoint name, not just the method name. For instance, the snippet below is in the urls.py file of the app: router.register( r"template", TemplateViewSet, basename="download-template", ) urlpatterns = router.urls So if the final endpoint urls are /template/download/ and /template/upload/, then the list of endpoints that use caching_func should be ["/template/download"]. Please describe how you think I can achieve this. -
Django logger not logging log levels below Warning
I am trying to configure logger in the Django Framework. I have changed the logging level to DEBUG in both handler and logger and still the INFO log is not getting logged. It only shows log upto Warning and not further from there. # app/views/test.py # def test() print("#"*10, logger.level,logger.name) #Log level is 10 when printed logger.info("This is an informational message.") logger.debug("This is a debug message.") logger.warning("This is a warning message.") logger.error("This is an error message.") logger.critical("This is a critical message.") Setting.py file log dict LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '{levelname} {asctime} {module} {message}', 'style': '{', }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'verbose', 'level':'DEBUG' }, }, 'loggers': { 'django': { 'handlers': ['console'], 'level': 'DEBUG', }, 'app': { 'handlers': ['console'], 'level': 'DEBUG', }, }, } Output: WARNING 2023-12-05 07:06:46,934 test This is a warning message. ERROR 2023-12-05 07:06:46,935 test This is an error message. CRITICAL 2023-12-05 07:06:46,935 test This is a critical message. The INFO and DEBUG log level message is not logged. -
How long does the `httpx.AsyncClient` can "live" without closing the event loop?
I have an endpoint in Django that orchestrates a bunch of API calls to other underlying services. I intend to use a long-lived instance of httpx.AsyncClient - which will be ultimately responsible for the API calls. class Api: # for historical reasons, this class has both sync and async methods ... AsyncApi = partial(Api, async_client=httpx.AsyncClient(timeout=30)) class MyViewSet(viewsets.GenericViewSet): @action(...) def merge(self, request: Request) -> Response: ... result = async_to_sync(merge_task)(..., api=AsyncApi(jwt_token=request.auth)) ... I'm doing some tests in a dummy server and I can see that sometimes merge_task captures RuntimeError('Event loop is closed') when calling api (or, ultimately, the long-lived instance of httpx.AsyncClient) so I'd bet that the loop for httpx.AsyncClient is closed after some time and there's no issue with asgiref's async_to_sync. Am I correct? If so, the only solution is to instantiate httpx.AsyncClient on every request? I tried do call merge_task using the endpoint but it captured RuntimeError('Event loop is closed'). The expectation is to not raise any error related to async programming -
Pytest, get IntegrityError when inserting ForeignKey by id
I have such table structure class ParentModel(models.Model): symbol = models.CharField(max_length=255, primary_key=True) name = models.CharField(max_length=200) class ChildModel(models.Model): parent_instrument = models.ForeignKey( to=ParentModel, on_delete=models.SET_NULL, null=True, blank=True, ) instrument = models.ForeignKey( to=ParentModel, on_delete=models.SET_NULL, null=True, blank=True, ) Then I run my pytest with empty database, where I test such logic try: ChildModel.objects.update_or_create( parent_instrument_id=symbol1, instrument_id=symbol2, ) except IntegrityError: self._create_instrument(symbol1, symbol2) I don't get IntegrityError. ChildModel is just saved without existing ParentModel symbol. Is it possible to avoid such behaviour? -
How can I change the delimiters in .vue file?
I'm trying to implement the signup function with django and vue. Below is the Signup.vue It only displays like {% csrf_token %} [[ form.as_p ]]. How can I show the form? <template> <div> <h1>SignUp</h1> <form method="POST"> {% csrf_token %} [[ form.as_p ]] <div class="mt-3"> <button type="submit" class="btn btn-primary">SignUp</button> </div> </form> </div> </template> <script> export default { delimiters: ['[[', ']]'], data() { return { form: {}, }; }, }; </script> The form is defined by using the CreateForm and the UserCreationForm as below. class SignUpView(CreateView): form_class = SignUpForm template_name = "Signup.vue" success_url = reverse_lazy("home") def form_valid(self, form): response = super().form_valid(form) username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") email = form.cleaned_data.get("email") user = authenticate(username=username, password=password, email=email) login(self.request, user) return response class SignUpForm(UserCreationForm): class Meta: model = User fields = ["username", "email", "password"] I had used delimiters like {{ }}, so I changed it into [[ ]]. But it didn't fix. -
Django rest Framework
While working on a project I suddenly started receiving this : Exception Type: DoesNotExist Exception Value: Site matching query does not exist. Exception Location: C:\Users\SayantanDutta\Code\Register2\venv\Lib\site-packages\django\db\models\query.py, line 647, in get Raised during: dj_rest_auth.registration.views.RegisterView Python Executable: C:\Users\SayantanDutta\Code\Register2\venv\Scripts\python.exe This happens when I try to register a user using postman or some other API calls Not sure why the library file is raising this exception? -
How to Integrate GTM with Partytown in Django Template
I am trying to integrate my GTM tag using Django Template. Following is my current html snipped that is working perfectly fine without partytown integration. <head> <script> (function (w, d, s, l, i) { w[l] = w[l] || []; w[l].push({ 'gtm.start': new Date().getTime(), event: 'gtm.js' }); var f = d.getElementsByTagName(s)[0], j = d.createElement(s), dl = l != 'dataLayer' ? '&l=' + l : ''; j.async = true; j.src = 'https://www.googletagmanager.com/gtm.js?id=' + i + dl; f.parentNode.insertBefore(j, f); })(window, document, 'script', 'dataLayer', '<gtm-id>'); </script> </head> <body> <noscript> <iframe src="https://www.googletagmanager.com/ns.html?id=<gtm-id>" height="0" width="0" style="display:none;visibility:hidden"></iframe> </noscript> </body> Now i want to integrate it throught partytown approach, something I tried was following but doesnot work <script type="text/partytown" src="https://www.googletagmanager.com/gtag/js?id=YOUR-ID-HERE"></script> <script type="text/partytown"> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'YOUR-ID-HERE'); </script> I just replaced my GTM ID in above template, this is the piece of code given in their documentation. If any one can integrate the conventional GTM code into the above partytown snipper please help, Im new to this library. Also note that I have integrated partytown library in my project so that is not a problem. No errors there just dont know how to integrate it. Thanks in advance -
Django site wide caching with vary on Cookie header caching per user response due to third party cookies
I am currently trying to set up the per-site-cache, it all seemed to work fine locally but once I moved it onto test servers with google analytics I noticed that it wasn't serving pages from the cache as expected. After a bit of digging I realised that this was due to another third party app that we are using (and need) that was accessing the session middleware, if the session middleware is accessed then Django will add 'Cookie' to the vary headers: # django/contrib/sessions/middleware.py if accessed: patch_vary_headers(response, ('Cookie',)) HTTP header: Vary: Cookie, Accept-Language The issue I have is that when Django is generating the cache key it is looking at all the cookies that are in the request, including third party ones (e.g. google analytics) which are nothing to do with Django and which do not impact on rendering the view. I don't want to monkey patch the third party Django app that we are using to stop is accessing the session. I could patch the vary headers to remove the vary on cookie header completely but I think that if the session middleware is setting the header then it is probably safer to leave it alone and just filter … -
Long running Django Celery task close DB connection
I have a Django Celery task that performs long-running operations and sometimes loses connection to the database (Postgres). the task looks like something like this: @app.task(name='my_name_of_the_task') def my_long_running_task(params): with transaction.atomic(): object_list = self.get_object_list_from_params(params) for batch in batches(object_list): self.some_calculations() MyObject.objects.bulk_create(objs=batch) # <- here connection could be lost I want to ensure the connection (but also be able to unit test this code). For example: @app.task(name='my_name_of_the_task') def my_long_running_task(params): with transaction.atomic(): object_list = self.get_object_list_from_params(params) for batch in batches(object_list): connection.connect() self.some_calculations() MyObject.objects.bulk_create(objs=batch) # <- here connection could be lost This would work (because it always opens new connections) but the unit test throws the error that can't roll back on teardown. I am thinking about @app.task(name='my_name_of_the_task') def my_long_running_task(params): with transaction.atomic(): object_list = self.get_object_list_from_params(params) for batch in batches(object_list): try: self.some_calculations() MyObject.objects.bulk_create(objs=batch) # <- here connection could be lost except Exception e: connection.connect() MyObject.objects.bulk_create(objs=batch) # retry this insert but is there a better way to handle this? -
Does nest js provide anything that runs after saving, updating or deleting, like how django signals provides?
I am running a project with nest js and prisma orm. Suppose I am creating a post record like following: // Query the database to create post ------------------------------------------------------- try { post = await this.prisma.post.create({ data: { uuid: uuidv4(), author: createPostDto.author, categoryId: postCategory.id, title: createPostDto.title, content: createPostDto.content, createdAt: new Date(), updatedAt: new Date(), } }) } catch (err) { this.logger.error(err); throw new InternalServerErrorException("Failed to create the post"); } After creating a record I want to run some perticular code. suppose I want to send notification to admins by calling sendNotification() method. But I don't want to call this method from inside an api. I know that django signals provide similar feature that can be used to run some part of code after creating, updating, or deleting a row. But I don't know what should be aprropeiate in the case of nest js. -
Django program gets stuck on get request, needs to be interrupted with Ctrl C to continue
I have tried everything I can possibly think of but I don't know what the solution is. I have a django application which running on my local network and receives requests from a react app. When the page loads tables (around 10 requests) the server seems to work quite well but randomly gets hung. When it gets hung it doesn't reach the view (the print statement doesnt run: def f(request): start_time = time.time() print('Received GET request')) and the moment I interrupt it a backlog of get requests like: Received GET request <WSGIRequest: GET '/api> Received GET request <WSGIRequest: GET '/api> Received GET request <WSGIRequest: GET '/api> Received GET request <WSGIRequest: GET '/api> Received GET request <WSGIRequest: GET '/api> which print in one go and then all the remaing requests are filled. Sometimes the requests with large responses crash, but sometimes even '/' hangs which only returns a hello world for me to test the server I am using a conda environment with some: asgiref 3.7.2 pyhd8ed1ab_0 conda-forge django 4.2.7 pyhd8ed1ab_0 conda-forge django-cors-headers 4.3.1 pyhd8ed1ab_0 conda-forge django-silk 5.0.4 pyhd8ed1ab_0 conda-forge djangorestframework 3.14.0 pyhd8ed1ab_0 conda-forge memory_profiler 0.58.0 pyhd3eb1b0_0 numexpr 2.8.7 py310h2cd9be0_0 pip 23.3.1 py310haa95532_0 pyodbc 4.0.39 py310hd77b12b_0 python 3.10.13 he1021f5_0 sqlite 3.41.2 … -
Setting value for template variable in django
I am using a for loop in django template. My logic is based on the previous value of item in the for loop. This is for comparing the previous value of that item with current value of the item, while the for loop iterate. Below mentioned is my requirement. Can anybody please help me with this code in django. Note: I am NOT using jinja, only django. Thanks. {% set var_name=0 %} {% for name in employees %} {% if var_name != name %} <td> {{ name }} </td> {% varname=name%} {% else %} <td> </td> {% endif %} {%endfor%} -
Where to pass context data in Response (Django)
I am wondering how to pass some context data to response in Django. I have this endpoint: /api/facebook/user/ which returns data like this: HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "facebook_account_id": "176890406129409", "first_name": "Ivan", "last_name": "K", "token_status": "active", "facebook_access_token": 1 }, { "facebook_account_id": "123123123", "first_name": "Ivan", "last_name": "FFFF", "token_status": null, "facebook_access_token": null }, { "facebook_account_id": "123123", "first_name": "Test", "last_name": "test", "token_status": null, "facebook_access_token": null } ] Here is my list serializer: class FacebookUserListSerializer(ModelSerializer): token_status = SerializerMethodField() class Meta: model = FacebookUser fields = ["facebook_account_id", "first_name", "last_name", "token_status", "facebook_access_token"] def get_token_status(self, obj): try: facebook_token = obj.facebook_access_token if facebook_token: return "active" if facebook_token.is_active else "inactive" except FacebookToken.DoesNotExist: return None Here is my list view: def list(self, request, *args, **kwargs): response = super().list(request, *args, **kwargs) data = response.data inactive_accounts = sum(1 for account in data if account.get("token_status") == "inactive") accounts_without_token = sum(1 for account in data if account.get("token_status") is None) context = {"inactive_accounts": inactive_accounts, "accounts_without_token": accounts_without_token} # Is this the correct way of passing context data to a response? response.context_data = context return response In list view, in the "context" variable, I am attempting to pass data to the frontend, but I am sure that I … -
Handling concurrent connections
I thought of implementing a game lobby (similar to chess.com). A player randomly paired with another player . I implemented this with a queue . When a new Request arrives , it checks queue and pairs to front element if any player exists in queue . Later I realized that this fails in real world as concurrent requests try to connect with same front element leading to various problems . My question is How real world game lobbies handle this problem ? Is there a way to Handle concurrent connections ? Any help is appreciated :) -
save method in django not saving data,field changes
i have tried all i think i should but my django model is not updating. The save() method is not working even though there seem not to be an error. #models.py class ApplicantDetails(models.Model): user = models.OneToOneField(User,null=True,blank=True, on_delete= models.SET_NULL,related_name='applicant') phone = models.CharField(max_length=200, null=True,blank=True) program = models.ForeignKey(Course,null=True,blank=True,on_delete= models.SET_NULL,related_name='courses') application_date =models.DateTimeField(auto_now_add=True,null=True,blank=True) nationality =CountryField(blank=False, null=False) passport_photo = models.FileField(upload_to="user_photo/", blank=True, null=True) #passport= models.CharField(max_length=200,choices=job_type_choices,null=True,blank=True) is_passport = models.BooleanField(default=False) is_credentials = models.BooleanField(default=False) is_address = models.BooleanField(default=False) is_emergency = models.BooleanField(default=False) is_worked_exp = models.BooleanField(default=False) is_additional = models.BooleanField(default=False) is_document = models.BooleanField(default=False) application_ID =models.CharField(max_length=200, null=True,blank=True) def __str__(self): user_name = self.user if self.user else "Unknown" user_first_name = self.user.first_name if self.user else "Unknown" user_last_name = self.user.last_name if self.user else "Unknown" return f"{user_name} {user_first_name} {user_last_name}'s Applicant Details" def save(self, *args, **kwargs): if not self.application_ID: nationality_prefix = self.nationality.code if self.nationality else '' phone_suffix = str(self.phone)[-4:] if self.phone else '' username_suffix = str(self.user.username)[:4] if self.user else '' uuid_part = str(uuid4())[:4] date_suffix = self.application_date.strftime('%y') if self.application_date else '' self.application_ID = nationality_prefix + phone_suffix + username_suffix + uuid_part + date_suffix super().save(*args, **kwargs) class Meta: verbose_name_plural='Applicant Details' class ApplicantPassport(models.Model): VISA_CHOICES = [(True, 'Yes'), (False, 'No')] user = models.ForeignKey(User, null=True, on_delete=models.CASCADE, related_name='passport_detail') middle_name = models.CharField(max_length=200, null=False, blank=False) dob = models.DateField(null=True, blank=True) passport_num = models.CharField(max_length=200, null=False, blank=False) place_of_issue = models.CharField(max_length=200, null=False, blank=False) place_of_birth … -
How do i resolve django staff and student dashboard work
Please fellow programmers, can someone help me write a Django staff and student dashboard where registered students who are attached to a particular staff can receive YouTube video uploads from their teacher's dashboard into their dashboard? # myapp/models.py from django.db import models class Staff(models.Model): name = models.CharField(max_length=100) class Student(models.Model): name = models.CharField(max_length=100) staff = models.ForeignKey(Staff, on_delete=models.CASCADE) class Video(models.Model): title = models.CharField(max_length=100) url = models.URLField() student = models.ForeignKey(Student, on_delete=models.CASCADE) # myapp/views.py from django.shortcuts import render, redirect from .models import Staff, Student, Video from .forms import VideoUploadForm def staff_dashboard(request, staff_id): staff = Staff.objects.get(id=staff_id) students = Student.objects.filter(staff=staff) context = {'staff': staff, 'students': students} return render(request, 'staff_dashboard.html', context) def student_dashboard(request, student_id): student = Student.objects.get(id=student_id) videos = Video.objects.filter(student=student) context = {'student': student, 'videos': videos} return render(request, 'student_dashboard.html', context) def upload_video(request, student_id): student = Student.objects.get(id=student_id) if request.method == 'POST': form = VideoUploadForm(request.POST, request.FILES) if form.is_valid(): video = form.save(commit=False) video.student = student video.save() return redirect('student_dashboard', student_id=student.id) else: form = VideoUploadForm() context = {'form': form, 'student': student} return render(request, 'upload_video.html', context) # myapp/urls.py from django.urls import path from .views import staff_dashboard, student_dashboard, upload_video urlpatterns = [ path('staff/<int:staff_id>/', staff_dashboard, name='staff_dashboard'), path('student/<int:student_id>/', student_dashboard, name='student_dashboard'), path('student/<int:student_id>/upload/', upload_video, name='upload_video'), ] -
Handle React routes from django, in Django, React Web App
I'm developing a Full-Stack Web App using Python Django as Backend and React Js as a backend. And Django Rest Framework for APIs. Now i'm facing issue of restricting users to access only routes having permissions. I want to handle react routes and navbar from django so that users access routes according to permissions given to them. Kindly guide me how can i do it. I want to handle react routes and navbar from django so that users access routes according to permissions given to them. Kindly guide me how can i do it. -
Display Django Form Fields depending on option selected using Javascript
I am working on a Django Project and I have the following html page which renders a form. I do not know much of Javascript, and I think I am going wrong somewhere in the Javascript Function or something else entirely. What I need to do is render the "id_mapnubparam01" field only when value of "id_mapnubfunction" is 'GETDATA'. I've split the if condition into 2 just to be clear, the first if condition for the "p" tag works perfectly fine. However using the same if then else logic the "id_mapnubparam01" does not do anything. Any help is appreciated. Thanks. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Data</title> </head> <body> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {% for field in form %} <div class="fieldWrapper"> <label>{{ field.label_tag }}</label> {{ field }} </div> {% endfor %} <input type="submit" value="Submit"> </form> <p id="demo"></p> <script> function myFunction() { var x = document.getElementById("id_mapnubfunction").value; if (x != 'GETDATA') {document.getElementById("demo").innerHTML = ""; } else {document.getElementById("demo").innerHTML = "You selected: " + x; } if (x != 'GETDATA') {document.getElementById('id_mapnubparam01').hide(); } else {document.getElementById('id_mapnubparam01').show(); } } </script> </body> </html>