Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to copy or read a file from the outside of the project file in Django?
I have created a basic ocr system. When a user uploads a PDF file to the system ocr read it and created an xlsm file with the same name. I am using remote control with Azure (Windows). I created a download button. When I click it, download the file with the same name, so it should work but appears an error because I want to read the file from the outside directory of the project. So, I should copy this file to my media dir, or I should read from there. This is my project: C:\Users\f-otc\PycharmProjects\otc This is the file that I want to download: C:\f\otc <a href= "{% static path %}" class="btn btn-outline-primary btn-sm" download>Download Report File</a> This is my button It gets the path correctly but gives an error when file downloaded. -
ListView isn't working in Django, Posts are not rendered
I am trying to render post_details and user_post HTML files but it is not rendering as expected. I can't see the post details or user posts in Django. It is rendering everything fine but not the post! Here is the code I am using: urls.py from django.contrib import admin from django.urls import path,include from . import views from .views import PostListView, UserPostListView, PostDetailView urlpatterns = [ path('', PostListView.as_view(), name='home'), path('user/<username>', UserPostListView.as_view(), name='user-post'), path('post/<int:pk>', PostDetailView.as_view(), name='post-detail'), path('login/',views.login_view, name='login'), path('logout/',views.logout_view, name='logout'), path('register/',views.register, name='register'), ] views.py from django.shortcuts import render,redirect from django.contrib.auth import login, logout,authenticate from django.shortcuts import render, get_object_or_404, HttpResponse from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.contrib.auth.models import User from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Post # from .forms import PostForm from itertools import chain # Create your views here. def home(request): context = { 'posts': Post.objects.all() } return render(request, 'index.html',context) def login_view(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if User is not None: login(request, user) return redirect('/') else: return render(request, 'login.html') return render(request, 'login.html') def logout_view(request): logout(request) return render(request, 'logout_view.html') def register(request): if request.method == 'POST': username = request.POST.get('username') email = request.POST.get('email') password = request.POST.get('password') user = … -
How to create file browser like google drive in django?
How to create a file browser like this in Django with Min.io or Amazon s3? -
Django : Changing settings in an exported csv file
I have implemented a button that will export the readings that are taken for a complex (to .csv) In the file that has been downloaded, the data is in the first cell only, separated by a coma. This is fixed in the .csv file by doing the following: Goint to data > get & transform data > from text/csv . 'select the file you wish to change' > transform data > save and close. Is there a way that I can change these settings in my exporting code. Views.py import csv def Avonleacsv(request): data =AvonleaClass.objects.all() response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="Avonlea_file.csv"' writer = csv.writer(response) writer.writerow(['Unit', 'Number of Units' ]) for avonleaclass in data: writer.writerow([ avonleaclass.unitNumber, avonleaclass.newReading, ]) return response -
type error module object is not iterable error in django
C:\IT Career\Python\shop>python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\THE KING\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 600, in url_patterns iter(patterns) TypeError: 'module' object is not iterable The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\THE KING\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\THE KING\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Users\THE KING\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\THE KING\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\THE KING\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Users\THE KING\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\THE KING\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\THE KING\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\THE KING\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 413, in check messages.extend(check_resolver(pattern)) File "C:\Users\THE KING\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\THE KING\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 412, in check for pattern in self.url_patterns: File "C:\Users\THE KING\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\functional.py", line 48, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\THE KING\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py", line 607, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'products.urls' from 'C:\IT Career\Python\shop\products\urls.py'>' does not appear to have any patterns in it. If you see valid patterns in … -
table not allow to create and edit in django
Django table not allow to edit and create. Before editing the table I changed is active true and taken user illyas But after saving is active false and taken user None.... WHY??? models.py class SignupCupon(models.Model): offer_for = models.CharField(max_length=20, default="Referral offer") cupon_code = models.CharField(max_length=50, unique=True) offer_price = models.PositiveIntegerField() is_active = models.BooleanField(default=False) which_user = models.OneToOneField(User, related_name="which_user_signup", on_delete=models.CASCADE, null=True, blank=True) taken_user = models.ForeignKey(User, related_name="signup_cupon_taken_user", on_delete=models.CASCADE, null=True, blank=True) create_at = models.DateTimeField(auto_now_add=True) def __str__(self): return "User: " + str(self.which_user) + " - Cupon: " + str(self.cupon_code) def save(self, *args, **kwargs): if self.cupon_code == "": self.cupon_code = generate_cupon() super().save(*args, **kwargs) admin.py from django.contrib import admin from .models import CategoryOffer, ProductOffer, CuponOffer, SignupCupon, ReferralCupon admin.site.register([CategoryOffer, ProductOffer, CuponOffer, SignupCupon, ReferralCupon]) -
How to run django project using gunicorn with TLSv1_2
I have django project with version 1.11 ,python 2.7 and used gunicorn (19.6) to run https service. Is it possible to change ssl protocol to TLSv1_2 ? I found only gunicorn 20.x version can change ssl protocol to TLS_V1_2 but it needs python 3.4+ thanks -
why loop already started in pyttsx3
this is my program engine = pyttsx3.init() voices = engine.getProperty('voices') engine.setProperty('voice', voices[1].id) engine.setProperty('rate', 150) def voice_alert(engine): engine.say('please wear mask') engine.runAndWait() the function voice_alert is called when while loop is started to run while True: if mask < withoutMask: t = threading.Thread(target=voice_alert, args=(engine,)) t.start() error: raise RuntimeError('run loop not started') RuntimeError: run loop not started -
Connecting mongodb atlas through mongoengine in django after hosting on EC2 apache2
I am trying to host django project on EC2 usnig apache2 which is using mongodb atlas as database. When I am running this locally on EC2 after openning some port like 8000, it runs properly but on apache it's giving error. Below is some TLSFeature error, I am facing mod_wsgi (pid=67994, process='tracky', application='ip-IP_ADDRESS|'): Loading Python script file '/home/tracky/tracky-api/tracky/wsgi.py'. mongodb+srv://username:password@host/dbname?retryWrites=true&w=majority mod_wsgi (pid=67994): Exception occurred processing WSGI script '/home/tracky/tracky-api/tracky/wsgi.py'. Traceback (most recent call last): File "/home/ubuntu/anaconda3/envs/tracky/lib/python3.6/site-packages/pymongo/pool.py", line 1278, in _get_socket sock_info = self.sockets.popleft() IndexError: pop from an empty deque During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/ubuntu/anaconda3/envs/tracky/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/ubuntu/anaconda3/envs/tracky/lib/python3.6/site- File "/home/tracky/tracky-api/trackyapi/urls.py", line 2, in <module> from .views import Tracky File "/home/tracky/tracky-api/trackyapi/views.py", line 16, in <module> from .serializers import GoalsSerializer, GoalSerializer File "/home/tracky/tracky-api/trackyapi/serializers.py", line 9, in <module> class GoalSerializer(DocumentSerializer): File "/home/tracky/tracky-api/trackyapi/serializers.py", line 11, in GoalSerializer uid = ReferenceField(User, write_only=True) File "/home/ubuntu/anaconda3/envs/tracky/lib/python3.6/site-packages/rest_framework_mongoengine/fields.py", line 217, in __init__ self.queryset = model.objects File "/home/ubuntu/anaconda3/envs/tracky/lib/python3.6/site-packages/mongoengine/queryset/manager.py", line 38, in __get__ queryset = queryset_class(owner, owner._get_collection()) File "/home/ubuntu/anaconda3/envs/tracky/lib/python3.6/site-packages/mongoengine/document.py", line 215, in _get_collection db = cls._get_db() File "/home/ubuntu/anaconda3/envs/tracky/lib/python3.6/site-packages/mongoengine/document.py", line 193, in _get_db return get_db(cls._meta.get("db_alias", DEFAULT_CONNECTION_NAME)) File "/home/ubuntu/anaconda3/envs/tracky/lib/python3.6/site-packages/mongoengine/connection.py", line 363, in get_db db.authenticate( File "/home/ubuntu/anaconda3/envs/tracky/lib/python3.6/site-packages/pymongo/database.py", line 1492, in … -
How do I get the prev data of a many to many field incase there is an Update
I'm trying to maintain a history of updates, I need to know how to get the previous data of a many to many field in the serializer update function for field,value in validated_data.items(): new_value=value old_value=getattr(instance, field) for some reason I'm getting None So,I also tried this old_value=validated_data.get('groups', None) and I got the new value instead So, any help is much appreciated, ty!! -
getting column 'is_routed' cannot be null error. Even thought it is set to default=0 in database
Im inserting some values into database table using orm here is what im doing: placeorder_userorder=UserOrder(order_status='Processing',listing_id=all_response[0],actual_cost=total_original_prize,order_total=total_final_prize,total_without_dc=total_original_prize, discount=total_final_discount,gst=all_response[0]['gst']) placeorder_userorder.save() where as 'is_routed' is set to default value to 0(along with many column) So im not mentioning 'is_routed' into my code and it is supposed to be 0 when new row added But im getting this error: django.db.utils.IntegrityError: (1048, "Column 'is_routed' cannot be null") -
Django - Passing multiple parameters into raw queries with %s format
In the project I am working on before we used a custom connector for MariaDB but now I have to use the default connector for MySQL in Django. The previous MariDb connector used ? For parameterization but MySQL for Django uses %s instead. I create the queries dynamically in the following way: def create_update_query(interpretation, record_id, table): query = "UPDATE `db-dummy`."+table+" " for index, key in enumerate(interpretation): if index == 0: query = query + "SET {0} = %s".format(key) else: query = query + ", {0} = %s".format(key) query += " WHERE record_id = " + record_id return query And this is a sample of a query created dynamically (there could be up to 30 parameters): UPDATE `db-dummy`.s_data SET s_id = %s, h_loss = %s WHERE record_id = 5877 And here comes the problem. With the MariaDB you could something like this: sd_query = create_update_query(interpretation, record_id, tableName) cursor.execute(sd_query, tuple(interpretation.values()) ) But I do not know how to do it with a %s parameterization. I couldn't find anything in the official documentation. EXTRA INFO: If for example we print(tuple(interpretation.values())), this is the outcome: ('SIC0575', '1') -
Is there any way I can pass args Value to pass in django celery periodic tasks?
I got certain following task to be executed from apps.users.email import ConfirmationEmail @shared_task def send_email(receipt, **kwargs): return ConfirmationEmail(context=kwargs).send(to=[receipt]) and send email is called in below function. I am having problem on passing args in periodic task as I could not find any docs regarding this def _email(self): token = RefreshToken.for_user(user=self.user_instance).access_token # get current site current_site = get_current_site(self._request).domain # we are calling verify by email view here whose name path is activate-by-email relative_link = reverse('activate-by-email') # make whole url absolute_url = 'http://' + current_site + relative_link + "?token=" + str(token) self.context = { 'user': self._user.username, 'token': absolute_url } receipent = self._user.email send_email.delay(receipent, **self.context) Above code works fine with redis but I want to send email every 2 minutes but I am confused on passing args while passing the periodic task job. Is the approach wrong or I am missing something? -
Deploy camera in production for a django application in aws with docker
I have a web application made in django that requires the user's camera to work, when I run the application locally it works and in the browser I ask the user for permissions for the camera, but when I put it into production in a docker container inside a AWS EC2 instance, the application works with an ip http address but does not ask for permissions for the camera. Dockerfile FROM python:3.8.3 ENV PYTHONUNBUFFERED 1 RUN mkdir /my_app_dir WORKDIR /my_app_dir ADD requirements.txt /my_app_dir/ RUN pip install --upgrade pip && pip install -r requirements.txt ADD . /my_app_dir/ docker-compose.yml version: '3' services: web: build: . command: python manage.py runserver 0.0.0.0:80 volumes: - .:/my_app_dir ports: - "80:80" http://33.12.99.22/ (example) -
How to solve "can only concatenate str (not "FieldFile") to str"
I am trying to get the file that I store all the images. I have 2 html, editingclaims and submitclaim. I am storing the images in models.py receipt = models.FileField(upload_to='receipts/%Y/%m/%D') Submitclaims allows user to submit an image, while editicingclaims claims allows user to edit the image. If user submits a new image in the editingclaims.html, it will overwrite existing ones. If there isnt any submitted image, it will display the old image from submitclaims.html This is my views.py # Edit a claim def editclaims(request,id): context = initialize_context(request) user = context['user'] # get original object claims = SaveClaimForm.objects.get(id=id) if request.method == 'POST': # update original object claims.name = request.POST['name'] claims.email = request.POST['email'] claims.claim = request.POST['claim'] claims.claimtype = request.POST.get('claimtype') claims.description = request.POST['description'] old_file = claims.receipt if os.path.isfile('receipts/%Y/%m/%D'+old_file): os.remove('receipts/%Y/%m/%D'+old_file) claims.receipt = request.FILES.get('receipt') claims.cheque = request.POST.get('Cheque') claims.status = request.POST['status'] # save it with original `ID` claims.save() return render(request, "Login/editclaims.html", {'claims':claims, 'user':user}) -
How to include non-Python dependencies in a Python Django deployment?
I am deploying a Django application using Heroku. One of my application's dependencies is the 'ta-lib' library, which is a Python wrapper for a library written in C. To get this to work locally, I simply had to download the underlying C library and the program would pick up what it needed from /usr/local and I had no problems. Library reference: https://mrjbq7.github.io/ta-lib/install.html Now, when I'm trying to push my files to Heroku via Git, the build fails at this library. Here is the terminal output, starting from where the errors began: remote: Building wheel for TA-Lib (setup.py): started remote: Building wheel for TA-Lib (setup.py): finished with status 'error' remote: ERROR: Command errored out with exit status 1: remote: command: /app/.heroku/python/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-ya1rkeoc/ta-lib/setup.py'"'"'; __file__='"'"'/tmp/pip-install-ya1rkeoc/ta-lib/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-e83ejfm_ remote: cwd: /tmp/pip-install-ya1rkeoc/ta-lib/ remote: Complete output (27 lines): remote: /tmp/pip-install-ya1rkeoc/ta-lib/setup.py:71: UserWarning: Cannot find ta-lib library, installation may fail. remote: warnings.warn('Cannot find ta-lib library, installation may fail.') remote: running bdist_wheel remote: running build remote: running build_py remote: creating build remote: creating build/lib.linux-x86_64-3.9 remote: creating build/lib.linux-x86_64-3.9/talib remote: copying talib/test_data.py -> build/lib.linux-x86_64-3.9/talib remote: copying talib/test_func.py -> build/lib.linux-x86_64-3.9/talib remote: copying talib/stream.py -> build/lib.linux-x86_64-3.9/talib remote: copying talib/__init__.py … -
Heroku passes the build but gives Application error
Hi I am trying to deploy a website on heroku. I successfully built it on heroku. When I try to deploy it gives me the Application Error when I check the log this is what I am getting: 2021-05-30T23:43:57.000000+00:00 app[api]: Build succeeded 2021-05-30T23:44:01.169958+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=cqthub.herokuapp.com request_id=1f7f7f68-028c-4101-a61c-dee410dc2429 fwd="75.157.7.173" dyno= connect= service= status=503 bytes= protocol=https 2021-05-30T23:44:10.322517+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=cqthub.herokuapp.com request_id=182f7faa-e19e-4693-919f-003e0600f42c fwd="75.157.7.173" dyno= connect= service= status=503 bytes= protocol=https I only mentioned 'favicon' in the footer: ..... </style> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.13/css/all.css" integrity="sha384-DNOHZ68U8hZfKXOrtjWvjxusGo9WQnrNx2sqG0tfsghAvtVlRW3tvkXWZh58N9jp" crossorigin="anonymous"> <link rel="icon" href="img/favicon.ico" type="image/x-icon"> <!-- Footer --> <hr> .... Can someone please tell me how to solve this issue? -
Django rest + React front
Currently, I am working with a group to try to create a website with a functional Django backend and a React frontend. We are using a user view set class UserViewset(viewsets.GenericViewSet, mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.ListModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin): permissions_classes = (permissions.AllowAny,) serializer_class = UserSerializer queryset = User.objects.all() This is where I am stuck, I haven't used viewsets or serializers before and I am at an impasse on where to go from here. I was hoping to get some clarification of how to add in a create/register user plus login and logout functions so that we can start messing with our api. Any help would be appreciated. -
Can't deploy Django on Heroku due to static error
Hello I am trying to launch my django website on heroku. I downloaded the heroku CLI, and I am running the following code on fish to resolve the error: heroku config:set DISABLE_COLLECTSTATIC=1 however I am getting the following error › Error: Missing required flag: › -a, --app APP app to run command against › See more help with --help Can someone please tell me how to resolve this issue? -
Make option in form disabled When already requested
I am building an web app that allows users to request items. The user will select the item, the location, the start date and end date of the borrowing in a form. I have the following model which I created the form from: class Request(models.Model): shootkit = models.ForeignKey(Shootkit, on_delete=models.CASCADE, null=True, blank=True) username = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) request_start_date = models.DateField('Start Date') request_end_date = models.DateField('End Date') location = models.ForeignKey(Location, on_delete=models.CASCADE) I have 5 Items in the database. And here's the model: class Shootkit(models.Model): shootkit = models.CharField('Shootkit', max_length=100, null=True, blank=True) And the def in views: def request_form(request): submitted = False if request.method == "POST": form = requestForm(request.POST) if form.is_valid(): stock = form.save(commit=False) stock.username = request.user stock.save() return HttpResponseRedirect('/request_form?submitted=True') else: form = requestForm(initial = {'username': request.user}) if 'submitted' in request.GET: submitted = True return render(request, 'request_form.html', {'form':form, 'submitted':submitted,}) The issue here is that I want to grey out (disable?) the items options which have been already requested. so I know that I can filter the date greater or equal than today in objects in the Request table so it means that the item still unavailable. But I am not sure how to block/disable the item. Can anyone help please? -
Which javascript library to choose if I want to use Django for backend?
Which js library should I use if I want server side rendering and both frontend and backend on the same host. Usually I use React+webpack alongside Django, and I serve the frontend as a static page but I want to try something different. I was thinking about exporting static pages with NextJs and then use Django to serve those pages individually (not sure if this would work though). Any thoughts or ideas? -
Hello!! i'm a beginer in django and python development. but when i want to use the commandd pipenv shell i have this error
pipenv shell Traceback (most recent call last): File "c:\users\qurrata\appdata\local\programs\python\python39\lib\runpy.py", line 197, in _run_module_as_main return _run_code(code, main_globals, None, File "c:\users\qurrata\appdata\local\programs\python\python39\lib\runpy.py", line 87, in run_code exec(code, run_globals) File "C:\Users\Qurrata\AppData\Local\Programs\Python\Python39\Scripts\pipenv.exe_main.py", line 7, in File "C:\Users\Qurrata\AppData\Local\Programs\Python\Python39\Lib\site-packages\pipenv\vendor\click\core.py", line 829, in call return self.main(*args, **kwargs) File "C:\Users\Qurrata\AppData\Local\Programs\Python\Python39\Lib\site-packages\pipenv\vendor\click\core.py", line 781, in main with self.make_context(prog_name, args, **extra) as ctx: File "C:\Users\Qurrata\AppData\Local\Programs\Python\Python39\Lib\site-packages\pipenv\vendor\click\core.py", line 700, in make_context self.parse_args(ctx, args) File "C:\Users\Qurrata\AppData\Local\Programs\Python\Python39\Lib\site-packages\pipenv\vendor\click\core.py", line 1212, in parse_args rest = Command.parse_args(self, ctx, args) File "C:\Users\Qurrata\AppData\Local\Programs\Python\Python39\Lib\site-packages\pipenv\vendor\click\core.py", line 1044, in parse_args parser = self.make_parser(ctx) File "C:\Users\Qurrata\AppData\Local\Programs\Python\Python39\Lib\site-packages\pipenv\vendor\click\core.py", line 965, in make_parser for param in self.get_params(ctx): File "C:\Users\Qurrata\AppData\Local\Programs\Python\Python39\Lib\site-packages\pipenv\vendor\click\core.py", line 912, in get_params help_option = self.get_help_option(ctx) File "c:\users\qurrata\appdata\local\programs\python\python39\lib\site-packages\pipenv\cli\options.py", line 27, in get_help_option from ..core import format_help File "c:\users\qurrata\appdata\local\programs\python\python39\lib\site-packages\pipenv\core.py", line 33, in from .project import Project File "c:\users\qurrata\appdata\local\programs\python\python39\lib\site-packages\pipenv\project.py", line 24, in from .environment import Environment File "c:\users\qurrata\appdata\local\programs\python\python39\lib\site-packages\pipenv\environment.py", line 16, in import pkg_resources ModuleNotFoundError: No module named 'pkg_resources' -
Check if a User type exists in ManyToManyField in Django?
I have a Course Model which contains a user who creates the course and contains a enrolled ManyToManyField which lets users enroll in the course. class Course(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='course_owner') enrolled = models.ManyToManyField(User) ... The user model contains two types - Teacher (Created the course) and Student (enrolls) class User(AbstractUser): is_student = models.BooleanField(default=True) is_teacher = models.BooleanField(default=False) I want a MyCourses View where the teacher can view his created_courses and the student can view his enrolled courses. def MyCourses(request): user = request.user courses = Course.objects.filter(user=user) context = { 'courses': courses } return render(request, 'classroom/mycourses.html', context) This works for the teacher part but how I can check if a student is enrolled in the course? Thanks. -
Why Django CK Editor easy image plugine not working?
I want image drag and drop functionality in my text editor so I added CK Editor easy image plugin. After adding easy image plugin, my whole text editor disappeared. Others plugin working properly but when trying to add easy image plugine, I am facing this issue. models.py text = RichTextUploadingField( # CKEDITOR.config.extraPlugins: extra_plugins=['notification','exportpdf','easyimage'], #notification and exportpdf working but when adding 'easyimage', my whole text editor is disappearing. # CKEDITOR.plugins.addExternal(...) #using my own path as they mention like this external_plugin_resources=[( 'someplugin', '/static/.../path-to-someplugin/', 'plugin.js', )], ) -
How to save multiple objects in Django models at once
What I'm trying to do is saving multiple scraped data(actor names) in my Actor table inside Django models. So far I've written the for loop below to achieve this goal but it only saves the last object. class Actor(models.Model): name = models.CharField(max_length=50) url = models.URLField() def __str__(self): return self.name def save(self, *args, **kwargs): i = 0 for num in range(5): title, year, actor_list = scraper(self.url) self.name = actor_list[i] super().save(*args, **kwargs) i += 1 I get the URL from users within a form, then save the form and send it to my models and the scraping begins. I scrape 5 actor names inside the scraper() function and append them to actor_list. But when I try to save the actor_list under the save function, it only saves the 5th actor which I think overwrites the previously saved objects. Is there something wrong with my for loop? or should I completely change my approach for this purpose? I'd also prefer to save the objects using Actor.objects.get_or_create() to skip the already existing objects, but I don't know how and where. I would appreciate it if someone could help me with this.