Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to restrict Django user account creation to given usernames / addresses / practical values?
We've set up Django user account creation / login through this tutorial, and we've restricted content to auth'd users only through the likes of {% if user.is_authenticated %} and if request.user.is_authenticated. All works great. But there's still nothing stopping anyone from going to the site and registering an account providing any values for username / email address / password. We want to restrict user account creation to specific usernames / emails / IPs / any practical value. Could we check if a value is in some whitelist by inserting something like if email in ['whitelistedemail@example.com']: somewhere? Something that emails out an invite link? We've found the docs on Permissions and Authorization and many SO questions on customizing functionality for types of users, yet we couldn't find any on restricting account creation itself, so perhaps we're missing something. We could start creating different types of users, but we're wary of getting ahead of ourselves by attempting a more advanced solution before figuring out this basic step. Are we approaching this in the right way? -
Django Dockerfile: the difference between Linux Run/Build dependencies
I'm writing a multi-stage / multi-profile Dockerfile for a Wagtail (Django) app. I took this example as my starting point. Also there are two similar examples: Bakery Demo App / AccordBox article. [01] RUN set -ex \ [02] && RUN_DEPS=" libexpat1 libjpeg62-turbo libpcre3 libpq5 \ [03] mime-support postgresql-client procps zlib1g \ [04] " \ [05] && seq 1 8 | xargs -I{} mkdir -p /usr/share/man/man{} \ [06] && apt-get update && apt-get install -y --no-install-recommends $RUN_DEPS \ [07] && rm -rf /var/lib/apt/lists/* [08] [09] ADD requirements/ /requirements/ [10] [11] RUN set -ex \ [12] && BUILD_DEPS=" build-essential git \ [13] libexpat1-dev libjpeg62-turbo-dev \ [14] libpcre3-dev libpq-dev zlib1g-dev \ [15] " \ [16] && apt-get update && apt-get install -y --no-install-recommends $BUILD_DEPS \ [17] && python3.9 -m venv /venv \ [18] && /venv/bin/pip install -U pip \ [19] && /venv/bin/pip install --no-cache-dir -r /requirements/production.txt \ [20] && apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false $BUILD_DEPS \ [21] && rm -rf /var/lib/apt/lists/* What's the essential difference between RUN_DEPS and BUILD_DEPS? Why libjpeg62-turbo-dev is inside the BUILD_DEPS and libjpeg62-turbo is inside RUN_DEPS list and not vice versa. How do I know what is the comprehensive list of all required RUN_DEPS / BUILD_DEPS for Wagtail … -
ModuleNotFoundError: No module named 'verify_email.apps'
I am getting an error while trying to run my Django projects. I have run the Django server before on my PC but ever since I installed Anaconda my projects would not work anymore. Please Help Below is the error message. (pyEnv) C:\Users\giova\Documents\giosroom\giosroom>python manage.py makemigrations Traceback (most recent call last): File "C:\Users\giova\Documents\giosroom\giosroom\manage.py", line 22, in <module> main() File "C:\Users\giova\Documents\giosroom\giosroom\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\giova\anaconda3\envs\pyEnv\lib\site- packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\giova\anaconda3\envs\pyEnv\lib\site- packages\django\core\management\__init__.py", line 395, in execute django.setup() File "C:\Users\giova\anaconda3\envs\pyEnv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\giova\anaconda3\envs\pyEnv\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\giova\anaconda3\envs\pyEnv\lib\site-packages\django\apps\config.py", line 212, in create mod = import_module(mod_path) File "C:\Users\giova\anaconda3\envs\pyEnv\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'verify_email.apps' -
Como dar permisos a mis usuarios por el admin de django?
Cuando intento darle algun permiso a algun usuario mediante el administrador de django me salta ese error cuando intento guardarlo, alguien me puede ayudar -
Django - How to filter queryset of model, using field two table away
I have three models: class Classroom(models.Model): classroom_subject = models.CharField(max_length=100) classroom_code = models.CharField(max_length= 5, default = '00000') teacher = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) student_name = models.CharField(max_length=100) classes = models.ManyToManyField(Classroom, blank = True) class WorkItem(models.Model): classroom = models.ForeignKey(Classroom, on_delete=models.CASCADE) work_description = models.CharField(max_length=500) date_assigned = models.DateField(auto_now_add=True, blank=True) time_assigned = models.TimeField(auto_now_add=True, blank=True) submission = models.ForeignKey(UserUpload, null = True, on_delete=models.CASCADE) I'm trying to return a queryset of WorkItem objects and filter the queryset through self.request.user. The model WorkItem is related to Classroom, and classroom is related to student. I have tried: x = WorkItem.objects.filter( classroom__student = self.request.user ) Basically the problem is how to reference a field two tables away, because from WorkItem, I need to reference Classroom, then from Classroom I need to reference Student. I don't know how to do this. Thanks for reading my question, any help would be greatly appreciated :). -
Correct way to get/create nested objects with DRF?
I have the following models: class Platform(models.Model): # Get key = models.CharField(max_length=32, unique=True) class PlatformVersion(models.Model): # Get or create platform = models.ForeignKey(Platform, on_delete=models.CASCADE) major = models.IntegerField(db_index=True) minor = models.IntegerField(db_index=True) build = models.IntegerField(db_index=True) class DeviceManufacturer(models.Model): # Get or create name = models.CharField(max_length=64, unique=True) class DeviceModel(models.Model): # Get or create manufacturer = models.ForeignKey(DeviceManufacturer, on_delete=models.CASCADE) platform = models.ForeignKey(Platform, on_delete=models.CASCADE) # ... # And many others POST JSON looks like this: { "device_model": { "manufacturer": { "name": "samsung" }, "platform": { "key": "android" } }, "version": { "platform": { "key": "android" }, "major": 8, "minor": 1, "build": 0 } } I have the following serializers: class PlatformSerializer(serializers.ModelSerializer): class Meta: model = Platform fields = ('name', 'key',) extra_kwargs = { 'name': { 'read_only': True, }, } def create(self, validated_data): return Platform.objects.get(key=validated_data['key']) class PlatformVersionSerializer(serializers.ModelSerializer): platform = PlatformSerializer() class Meta: model = PlatformVersion fields = ('platform', 'major', 'minor', 'build',) def create(self, validated_data): # ? pass class DeviceManufacturerSerializer(serializers.ModelSerializer): class Meta: model = DeviceManufacturer fields = ('name',) def create(self, validated_data): manufacturer, _ = DeviceManufacturer.objects.get_or_create( defaults={ 'name': validated_data['name'], }, name=validated_data['name'] ) return manufacturer class DeviceModelSerializer(serializers.ModelSerializer): manufacturer = DeviceManufacturerSerializer() platform = PlatformSerializer() class Meta: model = DeviceModel fields = ('manufacturer', 'platform') def create(self, validated_data): # ? pass I've marked in serializers … -
DJANGO 4.0.0 127.0.0.1/:81 GET http://127.0.0.1:8000/localhost:8000/media/movies/Vikings__Valhalla_Trailer_rsTJT2H.mp4 404 (Not Found)
I have a problem loading the video I get the following bug: 127.0.0.1/:81 GET http://127.0.0.1:8000/localhost:8000/media/movies/Vikings__Valhalla_Trailer_rsTJT2H.mp4 404 (Not Found) this is my showMovie.html: {% block content %} {% include 'partials/navbar.html' %} <main class='bg-primary_black h-full w-full '> {{ movie|json_script:"movie_data" }} <video src="" controls class="w-full h-screen player"></video> </main> <script type="text/javascript"> const videoEl=document.querySelector('video') const movie_data = JSON.parse(document.getElementById('movie_data').textContent); const url =new URL(location.href) const video_param = parseInt(url.searchParams.get("epi")) ? parseInt(url.searchParams.get("epi")) : 0 videoEl.setAttribute('src',`http:/localhost:8000/media/${movie_data[video_param].file}`) </script> {% endblock content %} And this is the view: class ShowMovie(View): def get(self,request,movie_id,*args, **kwargs): try: movie=Movie.objects.get(uuid=movie_id) movie=movie.videos.values() context = {'movie':list(movie)} return render(request,'showMovie.html',context) except Movie.DoesNotExist: return redirect('core:profile_list') it is a .mp4 file so store it in the static folder I don't know how to fix it. I've searched everywhere but can't find a workable solution. Everything else works great. Regards!! models.pyerror video movieDetail.html -
Is it possible to create a Django model from csv input with non-standardized column names/number of columns
I'm working on a project where the end user will provide a semi-standardized csv input to my program. By semi-standardized, I mean that most columns will always be present, but each csv has the potential to have an extra column or two that is unique to that csv alone. Because of this I don't think it's possible to pre-define an all encompassing Django model (I may be wrong, and would love to be shown otherwise), so my question is: is it possible to update/change the Django model's structure from views.py (or in some other way), based on the csv input file, to capture these non-standard columns and store the uploaded CSV to my db? If not, is there another way to go about solving this problem? -
Remove library root on venv
I created a project in django ear the venv folder The words library root appear why is it happening? How do I remove / cancel it? I want it to look like this without library root just venv Screenshot attached I tried to use this guide (link attached) the link Attached is a screenshot from my project On the screen marked in green, I removed line 1 I thought it would solve the problem but it did not help Could it be that it also created another problem? -
Django : How do you check if an user has the rights or not to Url
I am a newbee in django. In my website, when the user logs in, he is redirected to a page with a dropdown menu where he has to choose a contract on which he wants to work. After selecting the contract he is redirected to the specific homepage define with a pk value in the url.The pk value comes from the ID of the contract in the database. How can I check by a function or a decorator that the user has the rights to this ID. Because any user could right the numbers in the url and access to the page. Here is my view of the dropdown menu : @authenticated_user def selectcontrat(request) : context = initialize_context(request) form_client = SelectClient(request.POST, user=request.user) if form_client.is_valid(): id_contrat = request.POST.get("ID_Customer") return redirect(reverse('home', args=(id_contrat,))) context['form_client'] = form_client return render(request, 'base/selectcontrat.html', context) Here the views of the home page : @authenticated_user def home(request, id_contrat=None): context = initialize_context(request) return render(request, 'home.html', context) The urls : from django.urls import path from . import views urlpatterns = [ path('home/<int:id_contrat>/', views.home, name="home"), path('', views.loginAD, name="login"), path('signin', views.sign_in, name='signin'), path('callback', views.callback, name='callback'), path('selectcontrat', views.selectcontrat, name='selectcontrat') The model is the relation between a user and a group. which group the user … -
Django complex annotation comparing childrens
I have a DJANGO Profiles model and a Answer model with a foreignkey to Profile Imagine that every Profile will have multiple Answers like lists of integers What I want is to order my queryset by the most similar answers to mine. So I found this method (rmse) to compare arrays: np.sqrt(((list_a - list_b) ** 2).mean()) If the arrays are equals this returns 0 and so on.. How can I create a Annotation to Profiles queryset that compare my answers to others using this method above? -
Django redis cache cannot access redis cache set outside of django
I'm setting up redis as a docker service and connect to it through django-cache and python redis library. First: from django.http import HttpResponse from django.core.cache import cache def test_dj_redis(request): cache.set('dj_key', 'key_in_dj', 1000) return HttpResponse("Redis testing\n" "- in dj view: {}\n" "- in other: {}".format(cache.get('dj_key'), cache.get('py_key'))) Second: import redis r = redis.Redis( host='redis', port=6379 ) def cache_it(): r.set('py_key', 'key in py', 1000) print(r.get('py_key')) print(r.get(':1:dj_key')) print(r.keys()) If I run both of them first one by refresh the web page related to that django view second one by python cache_it(). In first, I cannot access 'py_key', it will return None. But second, I can see the cache set in django view. Django cache added a prefix to it and turn 'dj_key' into ':1:key_in_dj', but I can access it nonetheless. Also in second, the redis_r.keys() return [b'py_key', b':1:key_in_dj']. The value of the key 'py_key' remained the same, so how come I can't access it through django cache.get('py_key') -
auth.authenticate(username=username, password=password) returns none on DJANGO
I have a simple login url test needed to login: def test_logInUsingLoginAPI(self): self.user = UserFactory() data = dict(username=self.user.username, password=self.user.password) print("Client is sending") print("username: " + self.user.username) print("password: " + self.user.password) response = self.client.post('https://localhost:8000/api/users/login/', data, headers={'Content-Type': 'application/json'}, follow=True) print("Server responded with:") print(response.content) self.assertEqual(response.status_code, status.HTTP_200_OK) The factory looks like: class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User django_get_or_create = ["username"] username = factory.Faker("user_name") email = factory.Faker("email") is_superuser = False @factory.post_generation def password(self, create: bool, extracted: Sequence[Any], **kwargs): password = ( extracted if extracted else fake.password( length=42, special_chars=True, digits=True, upper_case=True, lower_case=True ) ) self.set_password(password) The backend view looks like this: @method_decorator(ensure_csrf_cookie, name='dispatch') class UserLoginView(APIView): permission_classes = [AllowAny] def post(self, request, format=None): data = self.request.data if not ("username" in data and "password" in data): return Response({"error": "Missing fields: username and password are all required fields"}, status=status.HTTP_400_BAD_REQUEST) username = data['username'] password = data['password'] user = auth.authenticate(username=username, password=password) print('Backend received. Trying to authenticate with') print('username: ' + username) print('password: ' + password) passwordFromUserName = User.objects.get(password=password).username print('extracted username from password: ' + passwordFromUserName) print('-------------------------------------') print("After authenticating with those username and password") if(user is None): print("user is not found") else: print("user is found") I keep on getting this on my console when I run pytest: I am not sure … -
Django project on Cloud Foundry not loading admin interface CSS
I have a simple Django project deployed with Cloud Foundry. The admin interface (the only interface used by my simple project) looks fine when running locally. When deployed, however, the CSS is visibly broken. The URLs for the CSS and JS assets return 404. Other answers to similar questions say that the solution is the collectstatic command. To run this in the context of Cloud Foundry, I type the following (obviously with the real app name and path): cf run-task app-name -c "python app-path/manage.py collectstatic" The output logged from this looks very promising: 128 static files copied to '/home/...path.../settings/static'. Yet, in spite of this apparent promise, the CSS is still broken. FYI, my settings include this: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] STATIC_URL = '/static/' PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_DIR, 'static') -
how to add slug to html template url tag in Django?
I want to have a URL path like this: www.example.com/html/html-introduction. Now there are two slugs here html and html-introduction. when i maually type in the slug in the url input, it works, but when i pass into a button in my html template it does not work and it shows this error Reverse for 'programming-languages-category' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['getting\\-started/(?P<prglangcat_slug>[-a-zA-Z0-9_]+)/$'] this is my template where i have the button i want to pass the slug into <div> {% for p in prglangcat %} <a href="{% url 'base:programming-languages-category' slug=p.prglangcat_slug.slug=p.prg_slug.slug %}" > <h4>{{p.title}}</h4> </a> {% endfor %} </div> views.py def index(request): prglangcat = ProgrammingLanguagesCategory.objects.all() context = { 'prglangcat': prglangcat } return render(request, 'base/index.html', context) def gettingStarted(request): prglangcat = ProgrammingLanguagesCategory.objects.all() context = { 'prglangcat': prglangcat } return render(request, 'base/getting-started.html', context) def programmingLanguageCategoryDetail(request, prglangcat_slug): prglangcat = ProgrammingLanguagesCategory.objects.get(slug=prglangcat_slug) context = { 'prglangcat': prglangcat } return render(request, 'base/language-category.html', context) def programmingLanguageTutorial(request, prglangcat_slug, prg_slug ): prglangcat = ProgrammingLanguagesCategory.objects.get(slug=prglangcat_slug) prglangtut = ProgrammingLanguageTutorial.objects.get(slug=prg_slug, prglangcat=prglangcat) context = { 'prglangtut': prglangtut, 'prglangcat': prglangcat } return render(request, 'base/tutorial-page.html', context) urls.py app_name = 'base' urlpatterns = [ path('', views.index, name="index"), path('getting-started/', views.gettingStarted, name="getting-started"), path('getting-started/<slug:prglangcat_slug>/', views.programmingLanguageCategoryDetail, name="programming-languages-category"), path('getting-started/<slug:prglangcat_slug>/<slug:prg_slug>/', views.programmingLanguageTutorial, name="tutorial-page"), ] models.py class ProgrammingLanguagesCategory(models.Model): title = models.CharField(max_length=100) icon … -
Django model (Questions) object is not iterable
error: 'Questions' object is not iterable models.py code: class Questions(models.Model): title = models.CharField(max_length = 150) slug = models.SlugField(max_length = 10, unique = True) body = models.TextField() category = models.ManyToManyField(Category, related_name = "questions") author = models.ForeignKey(User, on_delete = models.CASCADE) created = models.DateTimeField(auto_now_add = True) picture = models.ImageField(upload_to = "questions/%Y/%m/%d", null = True, blank = True) status = models.BooleanField(default = True) def get_absolute_url(self): return reverse("questions:ques_detail", args = [self.slug, self.id]) views.py code: def QuestionDetail(request, question, pk): question = get_object_or_404(Questions, slug = question, id = pk) return render(request, "questions/ques_detail.html", {"questions": question}) urls.py code: urlpatterns = [ path('<slug:question>/<int:pk>', QuestionDetail, name = "questiondetail") -
How to remove Django MPTT trailing slash at the end?
I've set up a simple path for categories url url(r'^kategorie/(?P<path>.*)', mptt_urls.view(model='categories.models.EcommerceProductCategory', view='ecommerce.views.category_view', slug_field='slug'), name='category_view'), models.py def get_absolute_url(self): return reverse('ecommerce:category_view', kwargs={'path': self.get_path()}) using this documentation: https://pypi.org/project/django-mptt-urls/ but when i go into an url lets say http://127.0.0.1:8000/ecommerce/category/x/ works just fine, but when i remove the trailing slash http://127.0.0.1:8000/ecommerce/category/x i get an error AttributeError at /ecommerce/category/x 'NoneType' object has no attribute 'get_ancestors' Do you have any idea how to not include the trailing slash? -
How to render a django message after page refresh
Hi i am trying to show a message but the django message is not showing. The way i want to access this is if i send a webhook to a function in python for example. ill send a webhook post request using postman , and i will receive the message But if i then go to my page it is not showing so my question is why is it working when i am using postman and not when using the browser, i also have a option to send the webhook request using a form on the app itself and ive added a refresh method as well but still nothing happpens. is there a way to get a message on django if the python function is triggered with a webhook? i am currently using 2 methods , both are working when using postman but neither works on the app itself method 1 messages.add_message(request, messages.INFO, 'LONG was placed.') {% if messages %} {% for message in messages %} <div class = "alert alert-{{message.tags}}">{{message}}</div> {% endfor %} {% endif %} and method 2 storage = messages.get_messages(request) for message in storage: a=(message) print(a) storage.used = False context = {'a':a} return render(request,'crodlUSDT/syntax.html',context) and then just … -
Create an object using Django Query in Shell
I am learning django. I am trying to create an object within Blog model using Django Query in Shell In the models.py file I have created the following models- from django.db import models # Create your models here. class Blog(models.Model): name = models.CharField(max_length=120) created_on = models.DateTimeField(auto_now_add=True) class Article(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=120) body = models.TextField() draft = models.BooleanField(default=False) I typed the following commands in the shell >>> from blog.models import Blog >>> blog = Blog(name='My Shell Blog') >>> blog.save() >>> article = Article(blog, title='My article from shell',body= 'I created this article from shell') >>> article.save() I got the following error- Traceback (most recent call last): File "/home/anshul/my-django/myapp_env/lib/python3.8/site-packages/django/db/models/fields/_init_.py", line 1988, in get_prep_value return int(value) TypeError: int() argument must be a string, a bytes-like object or a number, not 'Blog' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/anshul/my-django/myapp_env/lib/python3.8/site-packages/django/db/models/base.py", line 806, in save self.save_base( File "/home/anshul/my-django/myapp_env/lib/python3.8/site-packages/django/db/models/base.py", line 857, in save_base updated = self._save_table( File "/home/anshul/my-django/myapp_env/lib/python3.8/site-packages/django/db/models/base.py", line 970, in _save_table updated = self._do_update( File "/home/anshul/my-django/myapp_env/lib/python3.8/site-packages/django/db/models/base.py", line 1013, in _do_update filtered = base_qs.filter(pk=pk_val) File "/home/anshul/my-django/myapp_env/lib/python3.8/site-packages/django/db/models/query.py", line 1071, in filter return self._filter_or_exclude(False, args, kwargs) … -
502 Bad Gateway nginx/1.18.0 (Ubuntu) Django Digital ocean
I want to deploy my django project with Ubuntu and Digital Ocean. It's not the first time I do it but now I keep getting this error and I don't know what's causing it. I used this video as guide for the process: https://www.youtube.com/watch?v=US9BkvzuIxw. It's really annoying because the only message that I get is "502 Bad Gateway nginx/1.18.0 (Ubuntu)" and what I found on internet to solve it doesn't work. All nginx tests I run say it works correctly. This is the code where I think the error must be: /etc/nginx/sites-available/locallibrary server { server_name vvmwp.nl; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/sammy/locallibrary; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=sammy Group=sammy EnvironmentFile=/home/sammy/locallibrary/env WorkingDirectory=/home/sammy/locallibrary ExecStart=/home/sammy/env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ locallibrary.wsgi:application [Install] WantedBy=multi-user.target /etc/systemd/system/gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target Thanks in advance -
django-session-security not working for remember me
I'm trying to make remember me on login page, but not working. I tried set settings.SESSION_EXPIRE_AT_BROWSER_CLOSE=False on views.py or delete SESSION_EXPIRE_AT_BROWSER_CLOSE on settings.py, but nothing of that working. Can somebody help? settings.py SESSION_SECURITY_EXPIRE_AFTER=6 SESSION_SECURITY_WARN_AFTER=5 SESSION_EXPIRE_AT_BROWSER_CLOSE=True views.py def loginPage(request): if request.user.is_authenticated: return redirect('indexPage') else: if request.method == 'POST': salary_number = request.POST.get('salary_number') password = request.POST.get('password') user = authenticate(request, salary_number=salary_number, password=password) if user: login(request, user) remember_me = request.POST.get('remember_me') if remember_me: request.session.set_expiry(0) request.session.modified = True if password == '123456': return redirect('changePassword') else: return redirect('indexPage') context = {} return render(request, 'login.html', context) -
how can I add kakao pay to my django app?
hello in my app I did paypal but now I wanna add also kakao pay, I have tried somethings but doesn't work, is there any well explained turorials for that, and how can I install kakao pay in django app and work with that. Note : I have already registred to kakao developers and created an app there but can't understand how to make it work in the programming side -
Django automatically logouts when page reloads
I use SESSION_EXPIRE_AT_BROWSER_CLOSE = True for logging out the user once browser closes and it works fine in local computer but when I deploy the site and use this feature it immediately logouts the user once I login. I am using heroku as deployment server. Session settings in Settings.py :- SESSION_ENGINE = 'django.contrib.sessions.backends.cache' SESSION_COOKIE_AGE = 1000 SESSION_SAVE_EVERY_REQUEST = True SESSION_EXPIRE_AT_BROWSER_CLOSE = True -
Arithmetic Operations in django template
\<tr\> {% for i in portfolio %} \<!-- \<th scope="row"\>{{i.id}}\</th\> --\> \<td\>{{ i.stock }}\</td\> \<td\>{{ i.quantity }}\</td\> \<td\>{{ i.purchasedPrice }}\</td\> \<td\>{{ i.currentPrice }}\</td\> \<td\>{{ i.quantity\*i.currentPrice - i.quantity\*i.purchasedPrice|safe }\</td\> \<td\>\</td\> \</tr\> {% endfor %} I want to do display the mongodb fetched results in the above format but <td>{{ i.quantity*i.currentPrice - i.quantity*i.purchasedPrice|safe }</td> This line of code is thorwing error of "TemplateSyntaxError at / Could not parse some characters: i.quantity|i.currentPrice - i.quantityi.purchasedPrice||safe" How can fix this? -
How to give view authorization/access to a object of a model to different users by the creator of the object in django
I am doing an online classroom project in Django where I created a model named course which is accessible by teachers. When I create a class/new course it creates an object of that.Now I am trying to add students/users in a particular course/class object by inviting students or students can enroll using "clasroom_id"(a unique field I used in the model) just like we invite people in google classroom to join classes. How to do that? How to add course material to an individual course I added the models and views of the course object below. models.py class course(models.Model): course_name = models.CharField(max_length=200) course_id = models.CharField(max_length=10) course_sec = models.IntegerField() classroom_id = models.CharField(max_length=50,unique=True) created_by = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.course_name def is_valid(self): pass views.py def teacher_view(request, *args, **kwargs): form = add_course(request.POST or None) context = {} if form.is_valid(): course = form.save(commit=False) course.created_by = request.user course.save() return HttpResponse("Class Created Sucessfully") context['add_courses'] = form return render(request, 'teacherview.html', context) def view_courses(request, *args, **kwargs): students = course.objects.filter(created_by=request.user) dict = {'course':students} return render(request, 'teacherhome.html',dict)