Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
API endpoint for recent/new events in Django Rest Framework
I am trying to make an API endpoint for a mobile app in Django Rest Framework. The challenge I am facing is how to structure and Endpoint that will return the new events. So basically what I want to do is to make requests from the app every 5 seconds to fetch any new events. The events would be e.g a model is created, a model is updated, a model is delete and so on. -
Reduce database hits for Django podcast app
I'm building a podcast directory where episodes can be categorized. The code to generate a page for the podcast, a list of episodes, and a list of categories within each episode. A podcast can have a "Sports" and "News" category. And one episode might have "Sports", while another might have "Sports" and "News" as categories. The problem: I'm battering the database with looping within loops. I know there's a way more efficient way. Here's generally how the models are connected: class Podcast(models.Model): ... class Category(models.Model): podcast = models.ForeignKey(Podcast, on_delete=models.CASCADE) ... class Episode(models.Model): podcast = models.ForeignKey(Podcast, on_delete=models.CASCADE) categories = models.ManyToManyField(Category, blank=True) ... Then, when I load the podcast page and want to put a list of categories and episodes within it: class Podcast(models.Model): ... @property def get_categories(self): return self.category_set.all() @property def episodes_by_category(self): episodes_by_category = [] for category in self.get_categories: episodes = self.episode_set.all().filter(categories=category) episodes_by_category.append({ 'category': category, 'episodes': episodes, 'count': len(episodes), }) sorted_episodes_by_category = sorted(episodes_by_category, key = lambda i: i['count'],reverse=True) return sorted_episodes_by_category Then, when I load an episode page, I show other episodes that share the same categories: class Episode(models.Model): podcast = models.ForeignKey(Podcast, on_delete=models.CASCADE) categories = models.ManyToManyField(Category, blank=True) ... @property def get_categories(self): return self.categories.all().prefetch_related('episode_set').select_related('podcast') @property def related_episodes_by_category(self): episodes_by_category = [] for category in … -
Django third-party backends Access to API
This is my first project with python, and I am building an app with Django Rest Framework. I have made a lot of things in this project, but now I am stuck. I want to generate keys so third-party backends can have access to part of my API and I don’t know how to. For example: someone buys my product (done) and can generate x keys to give access to that API (then I will use DRF throttling to limit the requests). Do I generate keys like tokens and then they have to put it in the header to access? Or is it with Django REST Framework API Key ( https://florimondmanca.github.io/djangorestframework-api-key/ )? Any suggestions? Thanks, Pablo -
Get position of regex matches in database objects using Django
I have a Django app with a Postgres database that takes in user input, makes a regex based on this input, and returns the database entries that match this regex and the start and end positions of this match. The current implementation is something along the lines of: models.py: class SampleInputModel(models.Model): target_field = models.CharField() class SampleInputModelForm(ModelForm): class Meta: model = SampleInputModel fields = '__all__' class RecordObject(models.Model): record_name = models.TextField() record_string = models.TextField() views.py: find_regex_match(form_dict, one_record, terminating_word='keyword'): import re search_pattern = f'({form_dict['target_field']}).*(terminating_word)' for match in re.finditer(search_pattern, one_record.record_string): return '{}\t{}\t{}\t{}\n'.format( one_record.record_name, match.start(), match.end(), one_record.record_string[match.start():match.end()] ) def home(request): if request.method == 'POST': form = SampleInputModelForm(request.POST) if form.is_valid(): form = form.save(commit=False) form = model_to_dict(form) results = '' for one_record in RecordObject.objects.all(): results += find_regex_match(form_dict, one_record) return render(request, 'results.html', {'results': results}) else: form = SampleInputModelForm() return render(request, 'home.html', {'form': form}) This works and takes ~1.2 seconds on average to complete. However, I feel like there's a better way to handle the results instead of just passing a huge raw string to the template to render. I wanted to switch over to using some of the Django API for database filtering so that I can pass query sets to the templates. The new version of the … -
How to Stream mp4 from private bucket using django as a proxy?
I try to return a response to stream a video from a private bucket. To do that my django server will get the video from S3 and return a response. def get_video_from_fragment(self, request, custom_id=None): s3 = AmazonApi() streaming_body = s3.get_file_to_stream(fragment.video.file) if streaming_body is None: return Response({'details': "error retreiving the video"}, status=500) response = StreamingHttpResponse(streaming_content=streaming_body) response['Content-Disposition'] = f'attachment; filename="{fragment.video.filename}"' return response It work well for Chrome and Firefox but not for Safari. I read for Safari that the content need to be delivered with a 206 status code. The things is that my Nginx already deliver well the statics files (mp4 in this case) but not this kind of response. I tried to add response = StreamingHttpResponse(streaming_content=streaming_body, status=206) but in fact, it doesn't change anything. I test with a curl like they do on their documentation (from apple) I suppose that my nginx (or django) know how to manage my .mp4 files but don't know how to do with call that return a StreamingHttpResponse. Also I check how others website deliver their content and I see on my Safari console network tab a difference on the status. For example google website has a status code on Response Headers but mine are … -
Tell me correctly to display a detailed description
I don’t know how I used to live without this forum :) Tell me please, where did I go wrong? I created a behavior model in the views, created a URL, but when I click on the title, it does not go to a detailed description of the event. Could there be an error in what I inherit in DetailViews? I am attaching the code below Views: from django.shortcuts import get_object_or_404, render from django.views.generic import DetailView from django.views.generic.base import View from .models import Blog, Event # Create your views here. class EventView(View): def get(self, request): events = Event.objects.all() posts = Blog.objects.all() return render(request, "home/home.html", {"events": events, "posts":posts}) class BlogDetailView (View): def get(self, request, slug): posts = Blog.objects.get(url=slug) return render(request, "home/blog-detail.html", {"posts": posts}) class EventViewDetail(DetailView): model = Event template_name = "event/event-detail.html" slug_field = "name" Urls: from django.urls import path from . import views urlpatterns = [ path("", views.EventView.as_view()), path("<slug:slug>/", views.BlogDetailView.as_view(), name="home_detail"), path("event/<str:slug>/", views.EventViewDetail.as_view(), name="event_detail") ] HTML: <!-- Latest-Events-Sermons --> <section class="section-padding latest_event_sermons m-0"> <div class="container"> <div class="row"> <div class="col-md-6 col-lg-5"> <div class="heading"> <h3>Анонс событий</h3> <a href="#" class="btn btn-secondary btn-md pull-right">Показать все</a> </div> <div class="event_list"> <ul> {% if events %} {% for e in events %} <li> <div class="event_info"> <div class="event_date"> <span>{{ … -
Is it possible to write a site in html, and from django make databases?
If there is such an opportunity, then you can drop the link please, and if not, then explain how you can do this in python -
Django 3.x - which ASGI server (Uvicorn vs. Daphne)
I have a simple API-based web application written in Django, and I decided to upgrade Django from 2.x to 3.x. In Django docs there's a documentation page about ASGI servers, and two options are mentioned: Daphne and Uvicorn. Unfortunately they do not provide any benefits regarding a particular choice, so I'm confused when it comes to select one of them. I would like to hear opinions of people who have experience with both libraries, and I would like to ask mainly for opinion on performance and stability. And, basically, is it a big difference to use Uvicorn instead of Daphne? My server is running on Ubuntu, so Daphne seems to be the right choice, as it's designed to be used on UNIX system. -
django.core.exceptions.FieldError: Unknown field(s) (groups) specified for Account
Hi I was making a wagtail app but I have a problem overriding the user model with the abstract user and the BaseUserManager, trying to make migrations but it crashes and show this error on console: django.core.exceptions.FieldError: Unknown field(s) (groups) specified for Account It uses a package from django_countries And a choice to the account type Models.py from django.db import models from django_countries.fields import CountryField from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyAccountManager(BaseUserManager): def create_user( self, email, username, country, password=None ): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have a username') if not country: raise ValueError('Users must have country') user = self.model( email=self.normalize_email(email), username=username, country=country ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, country, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, country=country, account_type='MTR' ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): class AccountTypes(models.TextChoices): MASTER = 'MTR', _('Master') ADMINISTRATOR = 'ADM', _('Administrator') MODERATOR = 'MOD', _('Moderator') USER = 'USR', _('User') email = models.EmailField( verbose_name="email", max_length=60, unique=True, null=False, blank=False) username = models.CharField( max_length=30, unique=True, null=False, blank=False) photo = models.ImageField( verbose_name='photo', upload_to='profile_photos', null=True, blank=True) country = CountryField() account_type = models.CharField(max_length = … -
Django - sqlite - Delete attribute from model
I am a beginner in Django and up to now I was amazed how simple it was. I am running django 3 with an sqlite3 DB. I want to remove an attribute of one of my models. In this particular case it's "slug". models.py class Recipe(models.Model): title = models.CharField(max_length=100) creator = models.CharField(max_length=42) content = models.TextField(null=True) creation_date = models.DateTimeField(default=timezone.now, verbose_name="Creation date") photo = models.ImageField(upload_to="photos/") main_ingredient = models.ManyToManyField('Ingredient', related_name='recipes') slug = models.SlugField(max_length=100) class Meta: verbose_name = "recipe" ordering = ['creation_date'] def __str__(self): return self.title I just delete the line and ran python manage.py makemigration I got the following error SystemCheckError: System check identified some issues: ERRORS: <class 'recipes.admin.RecipeAdmin'>: (admin.E027) The value of 'prepopulated_fields' refers to 'slug', which is not an attribute of 'recipes.Recipe'. I suppose django does not want to delete the line from the DB. I have to do it manually then I tried this But it does not work for sqlite as explained here So far I was amazed by Django and this is a major drawback. Is there an easier way? what am I doing wrong? Thank you for your help -
Django Postgres search with SearchVectorField and TrigramSimilarity
I'd like to do efficient partial word matches with a large data set. I'm able to use SearchVectorField for speed and as a way to collect data from a few different fields. search_vector = SearchVectorField(editable=False) Thing.objects.update(search_vector=various_fields_vector) Thing.objects.filter(search_vector="something") Works quickly. However it doesn't perform partial word matches. Thing.objects.filter(search_vector="omething") Yields no results. I want to do something like Thing.objects.annotate(rank=TrigramSimilarity("search_vector", "omething")) However I get: No function matches the given name and argument types. You might need to add explicit type casts. Is there a way to index in some manner to perform these searches faster? -
Does Heroku WEB_CONCURRENCY need to account for ALL processes spawned by both Django AND task queue (such as; Huey, Celery) on the same dyno?
I am trying to deploy Django and Huey async task queue to the same dyno. I understand that people usually deploy a task queue to a separate dyno/container for independent scaling and what not. That reason for me doing this is because Huey is a light weight task queue and as such if there is a need for some async works or occasional scheduling, it could handle it (no need for heavy-weight like Celery in a separate dyno). Here is what sample Huey configuration in Django settings.py look like. I have used "process" as worker type and there are 3 of them (plus 1 mandatory consumer process) for a total of 4 for Huey. My question, do I have to account for that number in addition to Django process when setting WEB_CONCURRENCY? Or does the WEB_CONCURRENCY only apply to Django web request handler. I am not entirely how Gunicorn handle Django. -
(Django) How to reference through multiple layers of relationships? (potentially complex)
The following is a for a creative writing app. All aspects (characters, scenes, projects etc.) are recorded in the same model to allow for a simple sidebar directory. Each have extension models to add specific fields, so when an element is selected in the sidebar, the extension model is loaded as a form on the right. Extension model additional fields and universe model excluded for clarity. The problem is, I'm really stuck with restricting choices on a specific ManytoMany field. MODELS.PY user_information <only 1 record> current_universe <will be changed through a signal depending on the universe loaded> elements_type name <e.g. ID 1 = character, ID 2 = project, ID 3 = scene, ID 4 = draft> elements name = models.CharField(max_length=100) elements_type = models.ForeignKey(elements_type, on_delete=models.CASCADE) universe = models.PositiveSmallIntegerField() <default value will be set automatically to match current_universe> parent_ID models.ForeignKey('self', on_delete=models.CASCADE) <if the element is a scene, this will identify its draft; likewise with a draft and its project> extension_projects name elements_id = models.ForeignKey(elements, on_delete=models.CASCADE) characters = models.ManyToManyField(elements, limit_choices_to={'elements_type': 1, 'universe': ? User_information’s current_universe – record 1}) <don't know how to do this at the moment but that's not part of the question> extension_drafts name elements_id extension_scenes name elements_id characters = models.ManyToManyField(elements, … -
Template tag variables at django are not displayed
I’m building a blog and I’m new to django. I’m trying to build a post display page but tag variables are not working. urls.py urlpatterns = [ . . . path('post/<slug>/', views.post_detail, name='post_detail'), ] views.py . . . def post_detail(request, slug): all_posts= Post.objects.all() this_post = Post.objects.filter(post_slug=slug) return render(request = request, template_name = 'blog/post_detail.html', context = {'this_post':this_post, 'all_posts':all_posts}) . . . post_detail.html {% extends 'blog/header.html' %} {% block content %} <div class="row"> <div class="s12"> <div class="card grey lighten-5 hoverable"> <div class="card-content teal-text"> <span class="card-title">{{ this_post.post_title }}</span> <p style="font-size:70%">Published {{ this_post.post_published }}</p> <p>{{ this_post.post_content }}</p> </div> </div> </div> {% endblock %} Thanks from now! -
run a javascript function inside a python
I'm working on a project. I have a strings.py which has dicts like below: def bar(self): #do something STRINGS_ENGLISH = { 'title': 'foo' 'function': bar } then I wanna use this string in my Django template, I'll pass it through my context in the template named string. I know that If I wanna print the title in the HTML it's enough to write {{strings.title}}, but about the function I want to pass it to a button like that: <button onclick="{function()}">Do Something</button> but it's a python function! not a js function. so what should I do? -
ImportError after installing djangocms-blog: cannot import name 'python_2_unicode_compatible' from 'django.utils .encoding'
I currently installed django-cms and djangocms-blog. When I run migrate, it throws the following error. Some ressources suggest to install six, which however is already satisfied in my venv. I use the latest Python, pip and django versions. These are the guides I followed to set up djangocms and djangocms-blog. Any solution to this? Requirement already satisfied: webencodings in c:\users\jonas\appdata\local\prog rams\python\python38-32\lib\site-packages (from html5lib>=0.999999999->djangocms -text-ckeditor>=3.5->djangocms-blog) (0.5.1) Requirement already satisfied: asgiref~=3.2 in c:\users\jonas\appdata\local\prog rams\python\python38-32\lib\site-packages (from django>=1.1->django-taggit-templ atetags->djangocms-blog) (3.2.3) Requirement already satisfied: sqlparse>=0.2.2 in c:\users\jonas\appdata\local\p rograms\python\python38-32\lib\site-packages (from django>=1.1->django-taggit-te mplatetags->djangocms-blog) (0.3.0) Collecting django-js-asset Downloading django_js_asset-1.2.2-py2.py3-none-any.whl (5.8 kB) Building wheels for collected packages: djangocms-text-ckeditor, django-taggit-t emplatetags, django-filer, easy-thumbnails, django-sekizai, django-treebeard, dj ango-classy-tags, djangocms-admin-style, django-appdata Building wheel for djangocms-text-ckeditor (setup.py) ... done Created wheel for djangocms-text-ckeditor: filename=djangocms_text_ckeditor-3. 9.0-py3-none-any.whl size=2009460 sha256=7f2a93b1858ad9c776ea9d286bf96924070a8d7 03ffb5d4510f3b74d39ca57d2 Stored in directory: c:\users\jonas\appdata\local\pip\cache\wheels\0c\7b\1e\e3 908562c925cdc1dbcd7c4bd2447f8a11f6716a7d99f3c04b Building wheel for django-taggit-templatetags (setup.py) ... done Created wheel for django-taggit-templatetags: filename=django_taggit_templatet ags-0.2.5-py3-none-any.whl size=7824 sha256=798816cf8c5154b3cd9d133dd906c8e40945 53de30f114a76fe8829d08a7c66c Stored in directory: c:\users\jonas\appdata\local\pip\cache\wheels\82\a4\66\54 1f4c683657632200e1e8ea3a89698e88ede94c1232365f00 Building wheel for django-filer (setup.py) ... done Created wheel for django-filer: filename=django_filer-1.7.1-py3-none-any.whl s ize=1572351 sha256=89983e63dedf4ecef67b3c0f929f9cf53281cd232a8afa72e9c97e2b3d9e3 d34 Stored in directory: c:\users\jonas\appdata\local\pip\cache\wheels\01\26\cd\d8 64a98a0a882ae18c7c0551af158f82193a7e5daa88a86572 Building wheel for easy-thumbnails (setup.py) ... done Created wheel for easy-thumbnails: filename=easy_thumbnails-2.7-py2.py3-none-a ny.whl size=65532 sha256=b0c81ae967ea8073bba11192946e3e2a4af3928c5be5010445c6cf6 d21f37964 Stored in directory: c:\users\jonas\appdata\local\pip\cache\wheels\e4\3f\d4\3c 7af17dfe56f754d3fe9a3c610aaeff28eaad840778039d1f Building wheel for django-sekizai (setup.py) ... done … -
Rendering test as template: {% static %} not working
Django==3.0.6 I'm trying to let an admin user use template tags. I mean, like this: The filter gets id and renders a huge picture tag. views.py class PostDetailView(DetailView): model = Post def get(self, request, *args, **kwargs): self.object = self.get_object() post_body = "{% autoescape off %}\n{% load image %}\n{% load static %}\n" + self.object.body + "{% endautoescape %}" return HttpResponse(Template(post_body).render(Context())) # Breakpoint At breakpoint (shown in the code above) post_body equals: {% autoescape off %} {% load image %} {% load static %} <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.<p> {{ 1|img }} <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse … -
How can i create a notification system by django
Is there anyway to create a notification system for my website by django without django channels. If there is way how? -
Python + Django (total price and items are not changing!)
I have this in cart.html : Cart when I do the changes that I will show below the total price that's in the end with green plus is changed but the total price and items that are up are not showing at all after the changes I make ! so I do this : in class OrderItem I add : @property def get_total(self): total = self.product.price * self quantity return total then I go to my template -----> cart.html and I change the static total price of $40 to this : <div style="flex:1">${{item.get_total}}</div> and everything is alright with those changes but then I do changes as below in class Order I add : @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = sum([item.quantity for item in orderitems]) return total then I go to views.py and do this change : from context = {'items':items} ----> context = {'items':items, 'order':order} then do those changes in cart.html : <th><h5>Items: <strong>3</strong></h5></th> ------> <th><h5>Items: <strong>{{order.get_cart_items}}</strong></h5></th> <th><h5>Total: <strong>$43</strong></h5></th> -----> <th><h5>Total: <strong>${{order.get_cart_total}}</strong></h5></th> So from changes that I do from class Order and below nothing changes on runserver ! views.py models.py -
How to keep a SECRET_KEY secret in Django?
The Django documentation suggests keeping the SECRET_KEY in environmental variables rather than in the settings.py file. Why is this considered safer? The environmental variables are plain text-files which offer the same level of protection as settings.py. Even if the file rw permissions are set to root-only, I assume that this is not hard to break. My question is: which other options are there to store the SECRET_KEY? Or the master key used for encryption. From django-encrypted-secrets: django-encrypted-secrets works by using a key (stored locally in master.key file or read from the environment variable DJANGO_MASTER_KEY) and reading/writing secrets to the encrypted file secrets.yml.enc. If there is no other option than a plain text-file or environmental variable stored locally. How can this one be protected properly? -
django_select2 - limit the returned text to a specific field in module
I am using django_select2 in my application. I would like to search and display only according to one field of a model. models.py: class Venue(models.Model): venue_name = models.CharField(max_length=50) venue_city = models.CharField(max_length=50) venue_country = models.CharField(max_length=50) def __str__(self): return f"{self.venue_name}, {self.venue_city}, {self.venue_country}" forms.py: from django import forms from .models import from django_select2 import forms as s2forms class VenueForm(forms.ModelForm): class Meta: model = Venue fields = ['venue_name', 'venue_city', 'venue_country'] widgets = { 'venue_city': s2forms.ModelSelect2Widget(model=Venue, search_fields=['venue_city__icontains']), 'venue_country': s2forms.ModelSelect2Widget(model=Venue, search_fields=['venue_country__icontains']), } The above code successfully filter by venue_city field. Nevertheless, it returns the whole __str__(self). How can I make it to return only the city and country fields, so that users will see only the city or country from the dropdown list of the respective <input>s? -
Module not found error when trying to use shell_plus of django-extensions
I am trying to use the shell_plus that populates your shell with all your models. I put into INSTALLED_APPS: django_extensions. As soon as I try to run python manage.py shell_plus I get $ python manage.py shell Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\Cody\AppData\Roaming\Python\Python37\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Cody\AppData\Roaming\Python\Python37\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\Cody\AppData\Roaming\Python\Python37\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Cody\AppData\Roaming\Python\Python37\site-packages\django\apps\registry.py", line 122, in populate app_config.ready() File "C:\Users\Cody\AppData\Roaming\Python\Python37\site-packages\django\contrib\admin\apps.py", line 24, in ready self.module.autodiscover() File "C:\Users\Cody\AppData\Roaming\Python\Python37\site-packages\django\contrib\admin\__init__.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) File "C:\Users\Cody\AppData\Roaming\Python\Python37\site-packages\django\utils\module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "C:\Program Files (x86)\Python37-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\Cody\AppData\Roaming\Python\Python37\site-packages\django_extensions\admin\__init__.py", line 21, in <module> from django_extensions.admin.widgets import ForeignKeySearchInput File "C:\Users\Cody\AppData\Roaming\Python\Python37\site-packages\django_extensions\admin\widgets.py", line 7, in <module> from django.contrib.admin.templatetags.admin_static import static ModuleNotFoundError: No module named 'django.contrib.admin.templatetags.admin_static' If I am to comment out django_extensions and run python manage.py shell the shell works and defaults to ipython. Any … -
how to UPLOAD video file to DJANGO via program
model.py from django.db import models class Post(models.Model): video = models.FileField(upload_to='filesInput/') csv = models.FileField(upload_to='filesInput/') csvTimeL = models.CharField(max_length = 50, default = '00:00:02.02') csvTimeR = models.CharField(max_length = 50, default = '00:00:02.4') urlTimeL = models.CharField(max_length = 50, default = 3) urlTimeR = models.CharField(max_length = 50, default = 8) siteUrl = models.CharField(max_length = 300) def __str__(self): return self.siteUrl class Result(models.Model): inputData = models.ForeignKey(Post, on_delete = models.CASCADE) resVideo = models.FileField() def __str__(self): return self.resVideo.url So I want to upload videofile to Result.resVideo Here how I do it with TextField: python manage.py shell >>> from posts.models import Post, Result >>> a = Post.objects.get(id = 3) a.result_set.create(text = 'text') The problem is: I don't know how to explain django the connection of the video file to Post() and the video file itself. I also got the respond from another forum for uploading the video to Post(): from django.core.files.base import ContentFile from .models import Post video_name = 'video.webm' with open(video_name, 'rb') as f: video_content = f.read() instance = Post() instance.video.save(video_name, ContentFile(video_content)) instance.save() But i need to upload it to the Result.resVideo with "connection" to Post. -
Referral System on Django
I am working on a cashback website. I need help with creating referral links for users and tracking the number of users that registered through a users referral link. Also, Is there a way I can let the users get a fraction of what their referred users have earned? -
Template not showing context variable
I created an app called marketing app which customizes messages to be written on top of home page. My problem is that these messages are not showing when everything configured and I don't know why is that might be the template because {{ marketing_message.message }} is only not showing This is the model: class MarketingMessage(models.Model): message = models.CharField(max_length=120) active = models.BooleanField(default=False) featured = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) start_date = models.DateTimeField( auto_now_add=False, auto_now=False, null=True, blank=True) end = models.DateTimeField( auto_now_add=False, auto_now=False, null=True, blank=True) def __str__(self): return str(self.message[:12]) This is the view: from marketing.models import MarketingMessage class HomeView(ListView): model = Item paginate_by = 10 template_name = "home.html" def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) context['marketing_message'] = MarketingMessage.objects.all() return context This is the template: {% if marketing_message %} <div id="top-alert"class="alert alert-light" style="padding-top:85px; margin-bottom:-24px;"> <a href="#" class="close" data-dismiss="alert">×</a> <div class="container" style="text-align:center"> <strong> Marketing Message ! : </strong> {{ marketing_message.message}} </div> </div> {% endif %}