Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Drop Down List Values
I am using a helper.py to store all my queries and not taking advantage of the models.py. I have a form that inserts the value into my helper.py queries. Basically its filtering my search results. THe issue I am having is that once it filters the results. The drop down menu also shrinks with it. I would have to hit the back button to get a whole list to filter again. Is there a way I can filter the results and still keep all my drop down list values? Also, my page takes a very long time to load because the query executing has thousands of rows! Actual Result Drop down List: Chris Evan Patty Then if I choose Chris on the drop menu then Evan and Patty disappear when it narrows the query results and inputs Chris in my query. drop down list: Chris code helper.py def EmployeeBalancing(get_dropdown_value, procdate): cursor = connection.cursor() print(cursor.execute(f'''select distinct to_char(processingdate,'YYYY-MM-DD'), opstattypeskey, loginname, firstname, lastname, active_time, idle_time, items, keys, rejects,bypass,b_function, from ppc_data.emp_performance where to_char(processingdate,'YYYY-MM-DD') = '{procdate}' and loginname='{get_dropdown_value}' order by to_char(processingdate,'YYYY-MM-DD'), opstattypeskey, loginname, firstname, lastname, active_time, idle_time, items, keys, rejects,bypass,b_function desc ''')) query = cursor.fetchall() return query def EmployeeBalancing_Null(): cd = datetime.now().strftime('%Y-%m-%d') print(cd) cursor = … -
Django Run a Test By Its Filename
I have a django application with a test called test_thing.py Ive been running my test as such: python3 manage.py test --pattern="test_thing.py" Is there a way that I can run the test by its filename? I tried python3 manage.py test apiv2/tests/test_thing.py but I get an error: TypeError: 'NoneType' object is not iterable But when I run with the --pattern it works. -
Django multiple ManyToManyField with same model
When I only have one ManyToManyField the model works but when I add a second the serializer doesn't save. View: @api_view(['POST']) def update(request, pk): poll = Poll.objects.get(id=pk) serializer = PollSerializer(instance=poll, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) Model: class Poll(models.Model): title = models.CharField(max_length=200) option1 = models.CharField(max_length=200) option2 = models.CharField(max_length=200) option1total = models.IntegerField(default=0) option2total = models.IntegerField(default=0) owner = models.CharField(max_length=150, null=True) option1votes = models.ManyToManyField(User, related_name="option1votes") option2votes = models.ManyToManyField(User, related_name="option2votes") Example request: {'id': 17, 'title': 'What is your favorite programming language?', 'option1': 'Javascript', 'option2': 'Python', 'option1total': 2, 'option2total': 25, 'owner': None, 'option1votes': [], 'option2votes': [14]} -
HTML if div content is long show button
I have this django app I made, and it is a blog app. The blogs are quite long, so I want to be able to show a little and then more of the div's text if the blog is long. Here is my html: <a style="text-decoration: none;color: #000;" href="{% url 'post-detail' post.id %}"> <div id="content-blog"><p class="article-content">{{ post.content|safe }}</p></div> </a> I want something like this: <script> content = document.getElementById("content-blog"); max_length = 1000 //characters if(content > max_length){ //Do something } </script> So how would I get this to actually work. To summarize, I want this to check if a div is longer than 1000 characters, and if it is, to run the if statement above. Thanks. -
Reload DataTable content with jQuery ajax call
I have a DataTable and I want to filter it's content depending on what user selects in form. Here is the sample of code I use: $(document).on('click', '#filter_btn', filterList) function filterList (event) { event.preventDefault() var form_data = $('.filter-form').serialize() var url = window.location.origin + '/my-amazing-url/' $('#dataTable-x').DataTable({ ajax: { url: url, type: 'get', dataType: 'json', data: form_data } }) $('#dataTable-x').DataTable().ajax.reload() } On server side Django returns following: ... data = self.get_queryset().values() return JsonResponse(data) ... Yet nothing is changed. How should I modify the code? Thanks. -
Using Django REST on local network
I am wondering if it is reasonable to use Django REST on a private network with a local in-house server, using React.js/Native as a UI for a security system? I know Django REST, react, and other JS libraries so my thoughts are that it will be much easier/faster to develop this way. Are there any obvious issues with this? Has anyone else used a local Progressive Web App or local website for this type of system? With the amount of JS libraries out there I am sure the development would be much faster. Thanks! -
Django Class based view loading another form with data
I am not sure if I am using this Class based view correctly. What I am trying to do I thought was very simple. Basically is a form based on a model where I only use the 'User' field from: class OnSiteLog(models.Model): objects = models.Manager() user = models.ForeignKey(User, on_delete=models.CASCADE) checkIn = models.DateTimeField('checkin_date', null=True, blank=True) checkOut = models.DateTimeField('checkout_date', null=True, blank=True) notes = models.CharField(null=True, blank=True,max_length = 200) location = models.CharField(null=True, blank=True, max_length=200) autoCheckin = models.BooleanField(null=True, blank=True, default=False) class QueryUser(LoginRequiredMixin, FormView): model = OnSiteLog form_class = QueryForm template_name = 'log/query.html' success_url = '/' def post(self, request, *args, **kwargs): theRecord = OnSiteLog.objects.filter(user_id=24) print(theRecord[0].user) super(QueryUser, self).post(request, *args, **kwargs) return render(request, 'log/query.html', {'log':theRecord}) From there: the template is pretty simple with a crispy form: {% block content %} <div class="breadcrumb-area"> <!-- Background Curve --> <div class="breadcrumb-bg-curve"> <img src="{% static '/img/core-img/curve-5.png' %}" alt=""> </div> </div> <div class="container"> <h2> Query for User </h2> <div class="row"> <div class="col-sm"> {% crispy form %} </div> </div> <div class="row"> Logs <div class="col-sm"> <table class="table"> <tr> <th>User</th> <th>Check In</th> <th>Check Out</th> <th>Location</th> <th>Notes</th> </tr> {% for ins in log %} <tr> <td>{{ ins.user }}</td> <td>{{ ins.checkIn }}</td> <td>{{ ins.checkOut }}</td> <td>{{ ins.location }}</td> <td>{{ ins.notes }}</td> {% if request.user.is_superuser %} <td> <a href="{% … -
How can you output something when login is completed? Django
I'm trying to build a form that when the login button is clicked, it displays a login succesful message. Here is the thing, I want that when the "login" button is clicked, the user gets redirected and in the redirected page (which is the home page), it should show the message. How can you do this in Django? I've tried doing: {% if request.user.is_authenticated %} But the problem with this code is that the message appears each time, even when you reload the page. -
Django app not showing registered models in Admin page
I have tried everything I can think of and find on here but nothing seems to be able to get my models to register and show on my Django Admin page. Weird thing is I have another model that is already appearing on the Admin page that I've matched the syntax for but that one works and this other one does not. models.py class SimpleModel(models.Model): something = models.CharField('Simple Model', max_length=200, default='foobar') def __str__(self): return self.name admin.py from .models import SimpleModel admin.site.register(SimpleModel) settings.py INSTALLED_APPS = [ 'bootstrap4', 'app.apps.RequestsDashboardConfig', 'applications_dashboard', 'requests_dashboard', #'applications_dashboard.apps.ApplicationsDashboardConfig', 'requests_dashboard.apps.RequestsDashboardConfig', #"app.requests_dashboard", 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] You can see I've even tried multiple variations of the INSTALLED_APPS but even this still does not work. I don't even get any errors when I start the server with this series of commands after deleting the migrations. python3 manage.py flush python3 manage.py makemigrations python3 manage.py migrate python3 manage.py createsuperuser python3 manage.py runserver 0.0.0.0:80 I even tried deleting the entire DB, recreating it, and then running this again and still no luck! -
HTTPS Site not showing in browser, no exceptions for google-compute engine, django, nginx, gunicorn, lets encrypt, google domains
I am relatively new to google compute engine and to gunicorn and nginx with django. The problem is that I'm not getting any exceptions but my site doesn't host. I have used django, gunicorn, nginx, certbot/letsencrypt, google domains. The site worked with just gunicorn and nginx before I added google domain and certbot. Now I just get nothing via the browser. I can't tell what the issue is as I can't see anything in the logs. I've looked at part answers to similar problems but nothing seems to work, and I've tried looking at multiple setup articles. Can't seem to find the problem. NGINX settings: server { server_name <domain-name.com> <www.domain-name.com> ; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ij/djangoapp1; } location /media/ { root /home/ij/djangoapp1; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/<domain-name.com> /fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/<domain-name.com> /privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot access_log /var/log/nginx/example.access.log; error_log /var/log/nginx/example.error.log; } server { if ($host = <www.domain_name.com>) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = <domain-name.com> ) { return … -
event listener, singals , xml-rpc, cron django
I even don't know how to name it... I'm creating a django web service. User has to login. And I want to make a message system (it's more complex than messages, but the idea is similiar) - when I put sth into database table event and user_id is the same as logged - show it asap anywhere you are on web service. I thought about django_crontab, but this has 1 min step (too long) and it can't interfere with already opened page. I thought about xml-rpc, but I should add some javascript loop, which over and over checks some page which checks database - very resource-hungry. I'm looked at signals, it's ok to send signal - but how to get it from web? (if user is logged on two browsers - both should show message - if you want to ask) I have no starting point, please help mi with start. I thought about asynchronous xml-rpc which initiates connection, but if there's no message - there's no answer at all, but when record appears - it sents answer (if browser is already closed nothing happens). But it also should check table in loop. Generaly it is some kind of push … -
Django CMS - can't reorder children plugin
I have a plugin timeline with many children event plugins. For some reason, when I try to drag and reorder the event children plugins, I get a red line that appears and I'm not allowed to move the children plugin. Child Plugin is made up of: Title Description Date Image I can't find any posts about this, why does this happen and is there any way to fix this? (Parent) Timeline Plugin require_parent = True parent_classes = [...classes that exist for sure...] allow_children = True child_classes = ['TimelineEvent',] (Child) Timeline Event Plugin require_parent = True parent_classes = ['Timeline',] -
How to save a django model to database? save() method is not working
Hi I'm having trouble saving a django model to my database. My application uses Google signin for authentication and if the user's profile is not already in the database after authentication, it redirects them to a form where they can create a profile. The problem is whenever a user creates a profile it's not saving to the database. Below I've attached a picture of my admin page. (You will see that there is no Profile object) I've also attached my forms.py, models.py, and views.py views.py def register(request): user_email = Profile.objects.filter(email = request.user.email).exists() if request.user.is_authenticated: if user_email: return redirect('blog-home') else: if request.method == 'POST': profile = Profile() profile_form = CreateProfileForm(request.POST, instance=profile) if profile_form.is_valid(): profile.user = request.user profile.email = request.user.email profile_form.save() messages.success(request, f'Your account has been created! You are now able to log in') return redirect('blog-home') else: profile_form = CreateProfileForm() context = { 'form': profile_form } return render(request, 'users/register.html', context) models.py class Profile(models.Model): user = models.OneToOneField(User, null = True, on_delete=models.CASCADE) username = models.CharField(max_length = 15, default = '') first_name = models.CharField(max_length=20, default='') last_name = models.CharField(max_length=20, default='') email = models.CharField(max_length = 25, default = '') #image = models.ImageField(null=True, blank=True, upload_to='media/user/profile') #interests def __str__(self): return f'{self.first_name} Profile' forms.py class CreateProfileForm(forms.ModelForm): class Meta: model = … -
How to redirect to same page with get absolute url
My Detail and Create Views are working but i cant redirect to the same page after adding a commment under the post ... and i want to remove the 'post' field from my CommentForm so that i save the comment to a post object without the user choosing which post to save to // i did the same thing for the author of the comment but cant do it for the post itself my views class PostDetailView(DetailView): model = Post template_name='blog/post_detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) comments = Comment.objects.filter(post=self.object) context['comments'] = comments context['form'] = AddCommentForm() return context class CommentCreateView(CreateView): model = Comment fields = ['content','post'] template_name = 'blog/post_detail.html' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) my models class Post(models.Model): options = ( ('draft', 'Draft'), ('published', 'Published') ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish_date') publish_date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') content = models.TextField() status = models.CharField(max_length=10, choices=options, default='draft') class Meta: ordering = ('-publish_date',) def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() publish_date = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-publish_date',) def __str__(self): return f'Comment By {self.author}/{self.post}' def get_absolute_url(self): return reverse('post-detail', kwargs={'pk':self.post.pk}) my form class AddCommentForm(forms.ModelForm): content = … -
Getting user data in react from django API?
I am creating a simple blog front end to consume a django backend api. The way it is setup so I can access user data for each post is like this: post serializer: class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ['id', 'title', 'body', 'user'] depth = 1 react, where i display the data <Container variant='lg' maxWidth='lg'> <div className='posts'> <Typography key={post.id} variant='h3'> {post.title} </Typography> <Typography paragraph> {post.body} </Typography> <Typography paragraph> {post.user.user_name} </Typography> </div> </Container> Now, this does fit as a solution to my problem, in order to have the users username be displayed in post, but it exposes all user data, including email, password hash, last logged in, etc. What is better way to get user related data when using react? -
Like button using Ajax not working in Django project
I am stuck on a problem I am having trying to implement a 'Like' button into my django application. I have the functionality working for the models, and even in the html template the code works if I manually add a like from a user. It seems like my Ajax may be the issue, but I can't seem to figure out why. Here is my models.py: class Post(models.Model): direct_url = models.URLField(unique=True) post_url = models.URLField() post_title = models.CharField(max_length=300) time_posted = models.DateTimeField(default=timezone.now) user = models.ForeignKey(User, on_delete=models.CASCADE) class Like(models.Model): liker = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='likes') date_created = models.DateTimeField(default=timezone.now) def save(self, *args, **kwargs): super(Like, self).save(*args, **kwargs) And here is my views.py class PostListView(LoginRequiredMixin, generic.ListView): model = Post template_name = 'homepage/home.html' ordering = ['-time_posted'] context_object_name = 'posts' paginate_by = 6 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['now'] = datetime.now() context['likesbyuser'] = Like.objects.filter(liker=self.request.user) return context def likePost(request): if request.method == 'GET': post_id = request.GET['post_id'] likedpost = Post.objects.get(pk=post_id) # getting the liked post if Like.objects.filter(post=likedpost, liker=request.user).exists(): Like.objects.filter(post=likedpost, liker=request.user).delete() else: m = Like(post=likedpost, liker=request.user) # creating like object m.save() # saves into database return HttpResponse(likedpost.likes.count()) else: return HttpResponse("Request method is not a GET") This is part of the template, where I am putting the buttons … -
Django model importing issue
I'm new to Django. I've been trying to import my model.py into a custom management command file, but it tells me: Unable to import 'Educationa_Organization_Management_System.Subjects.models Here's my code in the custom command file : from django.core.management.base import BaseCommand from Educationa_Organization_Management_System.Subjects.models import Subject class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument("Subject_name") parser.add_argument("Instructor_name") parser.add_argument("prerequisites", action="store_true") parser.add_argument("Assistant_name") parser.add_argument("Course_description") parser.add_argument("Validation_date") parser.add_argument("SubjectNumberOfChapters") parser.add_argument("numberOfLecturesPerWeek") parser.add_argument("numberOfSectionsPerWeek") parser.add_argument("Subject_FullGrade") def handle(self, *args, **options): subject = Subject( name=options['name'], Instructor_name=options['Instructor_name'], prerequisites=options['prerequisites'], Assistant_name=options['Assistant_name'], Course_description=options['Course_description'], Validation_date=options['Validation_date'], SubjectNumberOfChapters=options['SubjectNumberOfChapters'], numberOfLecturesPerWeek=options['numberOfLecturesPerWeek'], numberOfSectionsPerWeek=options['numberOfSectionsPerWeek'], Subject_FullGrade=options['Subject_FullGrade'], ) subject.save() self.stdout.write(self.style.SUCCESS( "Subject has been successfully added to the database")) and here's my model.py file content: from django.db import models class Subject(models.Model): Subject_name = models.CharField(max_length=50, blank=False) Instructor_name = models.CharField(max_length=50, blank=False) prerequisites = models.BooleanField() Assistant_name = models.CharField(max_length=50, blank=False) Course_description = models.TextField() Validation_date = models.DateTimeField() SubjectNumberOfChapters = models.IntegerField(blank=False, null=False) numberOfLecturesPerWeek = models.IntegerField() numberOfSectionsPerWeek = models.IntegerField() Subject_FullGrade = models.IntegerField() And finally, Here're my folders: -
How to prepare a list for queryset (select2) from multiple m2m filed
One of my models has three columns which are M2M fields and each of these three M2M fields has different models. I want to get a dataset from this product attribute model as shown in the output SQU below. And this is the dataset I want to get as the queryset of the model form. I would be very grateful if someone could give me a little idea on how to do this. Or I'm not sure if the model design is right in the field of getting such a dataset, because I'm brand new to Django. class ProductAttributes(models.Model): product = models.ForeignKey('Product', blank=True, null=True, on_delete=models.SET_NULL) size = models.ManyToManyField('ProductSize', related_name = "productsize") colour = models.ManyToManyField('ProductColour', related_name="productcolour") cupsize = models.ManyToManyField('ProductCupSize', related_name="productcupsize") class ProductSize(models.Model): name = models.CharField(max_length=10) class ProductColour(models.Model): name = models.CharField(max_length=25) colour = models.CharField(max_length=15, blank=True, null=True) class ProductCupSize(models.Model): name = models.CharField(max_length=1) The way I query data from these three models. attrs = ProductAttributes.objects.filter(product=product_id).values('product', 'size__name', 'colour__name', 'cupsize__name') sku = [] for attr in attrs: att = {'id': '-'.join([str(attr['product']), str(attr['size__name']), str(attr['cupsize__name']), str(attr['colour__name'])]), 'text': '-'.join( [str(attr['size__name']), str(attr['cupsize__name']), str(attr['colour__name'])])} sku.append(att) output sku: [{'id': '108-32-B-Grey', 'text': '32-B-Grey'}, {'id': '108-32-C-Grey', 'text': '32-C-Grey'}, {'id': '108-32-B-White', 'text': '32-B-White'}, {'id': '108-32-C-White', 'text': '32-C-White'}, {'id': '108-34-B-Grey', 'text': '34-B-Grey'}, {'id': '108-34-C-Grey', 'text' : … -
Celery working with my app at local development but can't deploy onto heroku
I have my app which is running Celery and Redis and the function works fine when I run the app on localhost. However when I got to deploy and push onto heroku following the Heroku/Celery documentation it doesn't work. I've also had a look a various questions on here to see if I can figure it out but I'm a bit of a novice and can't seem to find what I need to do. I thought I would post the code as usually theres a really simple solution that I am missing. This is the code that works locally - celery.py - from __future__ import absolute_import import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DjangoProj.settings') app = Celery('DjangoProj') app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def celery_function(self): *does something* views.py def function(request): celery_function.delay() return render(request, "home.html") settings.py CELERY_BROKER_URL = 'redis://localhost:6379' If anyone could send me a step by step or something along those lines that would be great, I can't really seem to make sense of deploying it through the heroku documentation. -
How to avoid losing data from the Heroku database when I commit a change in my GitHub repo?
I have deployed a Django app on Heroku. Now my problem is that as the Heroku account is linked to my GitHub repo, so each time I commit a change in my repo, Heroku deploys the GitHub files and all the data stored on Heroku database is replaced by the data stored in the db.sqlite3 database of my Github repo. That is after deploying my app, suppose a user signs up, so his details are stored in the Heroku database but not in the db.sqlite3 database in my GitHub repo, so now if I commit any change to my GitHub repo then the Heroku database is replaced with the old data present in the GitHub db.sqlite3 database which don't have the data of the users who signed up. I tried deleting my db.sqlite3 and added it to .gitignore so that when I commit a change on GitHub, Heroku won't notice the database. But then I am getting application error while deploying my app since Heroku don't run migrations during deploy, so it needs the migration data from dq.sqlite3. So how can I avoid losing data from the heroku database when I commit a change to my GitHub repo? -
How to filter Django BooleanFields and display the results in a template
Brand new to Python/Django and have hit a wall trying to figure out how to only show posts marked as True in certain parts of the same template. For eg. I have a blog, the User can make posts but I want the posts marked as science_post, using a Django BooleanField, to be displayed separately from the rest of the blog posts. Here's what I have for my Post model: class Post(models.Model): title = models.CharField(max_length=31) content = models.TextField() thumbnail = models.ImageField() picture_description = models.CharField(max_length=100, default=True) displayed_author = models.CharField(max_length=25, default=True) shortquote = models.TextField() reference_title = models.ManyToManyField(References) publish_date = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE) slug = models.SlugField() science_post = models.BooleanField(default=False) def __str__(self): return self.title def get_absolute_url(self): return reverse("detail", kwargs={ 'slug': self.slug }) def get_love_url(self): return reverse("love", kwargs={ 'slug': self.slug }) @property def comments(self): return self.comment_set.all() @property def get_comment_count(self): return self.comment_set.all().count() @property def get_view_count(self): return self.postview_set.all().count() @property def get_love_count(self): return self.love_set.all().count() My idea was to simply filter out the posts marked science_post in the template using something along the lines of {% if science_post %} SHOW SCIENCE POST CONTENT HERE {% endif %} ...But this returns nothing. Any help or a point in the right direction with this would be … -
Django back-end scripts scheduling
I'm building a website with Django and among other things I want to display the latest news about a certain topic. I have a python script in the back-end that I would like to program to retrieve the latest news once every 1 hour for example. In the meantime I want to be able to display the most recently retrieved news. I'm doing this in order to avoid that the script is being activated every time someone opens my website. My script is in news.py: import pprint import requests import datetime import pandas as pd import dateutil.parser secret = "********" url = 'https://newsapi.org/v2/everything?' quote = 'Amazon' parameters1 = { 'q': quote, 'pageSize': 100, 'sortby': 'publishedAt', 'apiKey': secret, } response1 = requests.get(url, params=parameters1) response_json1 = response1.json() text_combined1 = [] for i in response_json1['articles']: if i['content'] != None: case = {'Source': i['source']['name'], 'Title': i['title'], 'url': i['url'], 'Published on:': dateutil.parser.parse(i['publishedAt']).strftime('%Y-%m-%d'), 'Image': i['urlToImage']} text_combined1.append(case) data_amazon = pd.DataFrame.from_dict(text_combined1) news1 = data_amazon.iloc[0] news2 = data_amazon.iloc[1] news3 = data_amazon.iloc[2] My views.py looks like this: from django.shortcuts import render from .news import * def dashboard(request): content = {'data': data, 'news1': news1, 'news2': news2, 'news3': news3} return render(request, 'dashboard.html', content) I'm new to web development but my understanding as … -
Factoryboy returns wrong field when using subfactory
I have a table FilmWork which is linked to a table Perosn via FilmWorkPerson table. I am trying to populate them with fake data I have basically used this example: https://factoryboy.readthedocs.io/en/rbarrois-guide/recipes.html#many-to-many-relation-with-a-through factories.py: class PersonTestFactory(DjangoModelFactory): class Meta: model = Person id = factory.Faker('uuid4') name = factory.Faker("sentence", nb_words=1) class FilmWorkTestFactory(DjangoModelFactory): class Meta: model = FilmWork id = factory.Faker('uuid4') title = factory.Faker("company") class FilmWorkPersoTestFactory(factory.django.DjangoModelFactory): class Meta: model = FilmWorkPerson movie_id = factory.SubFactory(FilmWorkTestFactory) person_id = factory.SubFactory(PersonTestFactory) class FilmWorkPersoTestFactory2(FilmWorkTestFactory): membership = factory.RelatedFactory( FilmWorkPersoTestFactory, factory_related_name='movie_id', ) But when I call FilmWorkPersoTestFactory2() , it returns an error: ['“Fisher, Smith and Ford” is not a valid UUID.']. I think it takes title instead of id and I do not understand how to point it to the correct field. -
Generate thumbnails HLS(.m3u8) python
What could be the effiecnt way of getting a screenshot of an hls live streaming link in python. I Have tried reading through different packages like this one ffmpeg python lib, but I haven't seen what I need exactly. A django solution would be better. -
Filter multiple ajax tables with one filter on Django
Hello and Thank you for your time, I recently started using django and need some help. I have multiple ajax-tables rendered in an html template as in the documentation: https://pypi.org/project/django-ajax-tables/ I have a table per view and render them in different divs of the same html page. All the models for this tables have a foreing_key of a model called Location, and all this child models have a date. I want a filter for this tables where I can enter Location and start_date and on submit(or on type|select) all tables get updated. What would be the best way to do this on Django?