Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
'BlogListView' object has no attribute 'object_list' in Django
I have a blog page with a list of posts that are paginated with ListView and on the same page I have a newsletter form where a uses can enter an email an be subscribed and I tried this in order to achive all this on the same page but I get this error and I don't know how to get rid of it. my view: class BlogListView(ListView): model = Post template_name = 'blog/blog.html' context_object_name = 'posts' ordering = ['-published_date'] paginate_by = 2 filterset_class = PostFilterForm post_search_title = None def post(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) email = request.POST.get('newsletter_email') if Newsletter.objects.filter(email=email).exists(): messages.warning(request, messages_text['email_exists']) else: Newsletter.objects.create(email=email) messages.success(request, messages_text['email_subscribed']) return redirect('blog') return render(request, self.template_name, context) def get_queryset(self): queryset = super().get_queryset() self.post_search_title = self.filterset_class(self.request.GET, queryset=queryset) return self.post_search_title.qs.distinct() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['post_search_title'] = self.post_search_title tags = Post.tags.most_common()[:8] context['banner_page_title'] = template_titles['blog_title'] context['page_location'] = template_titles['blog_path'] context['tags'] = tags return context the error AttributeError at /blog/ 'BlogListView' object has no attribute 'object_list' -
Django Rest Framework: append value to ListAPIView
Hello StackOverflow community, I've got following serializer and view: serializers.py class PricetrendSerializer(serializers.ModelSerializer): timestamp = serializers.DateTimeField() average_price = serializers.IntegerField() class Meta: model = Cars fields = ('timestamp', 'average_price') views.py class Pricetrend(generics.ListAPIView): queryset = Cars.objects.annotate(timestamp=TruncMonth('timestamp')).values('timestamp').annotate(average_price=Avg('price')) serializer_class = PricetrendSerializer filter_backends = (filters.DjangoFilterBackend, SearchFilter, OrderingFilter) filterset_class = PriceFilter search_fields = ['description'] ordering_fields = ['timestamp', 'average_price'] ordering = ['timestamp'] permission_classes = (permissions.IsAuthenticated,) Which is giving me the following output: { "count": 2, "next": null, "previous": null, "results": [ { "timestamp": "2020-04-01T00:00:00", "average_price": 90274 }, { "timestamp": "2020-05-01T00:00:00", "average_price": 99253 } ] } I would like to also aggregate the total average price and add it to the output, e.g.: { "count": 2, "next": null, "previous": null, "total_average_price": 125000, "results": [ { "timestamp": "2020-04-01T00:00:00", "average_price": 90274 }, { "timestamp": "2020-05-01T00:00:00", "average_price": 99253 } ] } Unfortunately, I do not know how this could be done as adding it to the serializer will result in having the total_average_price in every json object. I also tried to override the ListAPIView (get function) but this killed the built-in pagination :( I hope that somebody is able to help me find a neat way to solve this. -
querying between multiple django models
I have 3 models categories, badges, and reward. The users are awarded badges and are stored under reward. The user model is the default model provided by django. class BadgeCategory(models.Model): name = models.CharField(max_length=30) class Badge(models.Model): points = models.IntegerField(default=1) title = models.CharField(max_length=30) category = models.ForeignKey(BadgeCategory,on_delete=models.SET_NULL,null=True) class Reward(models.Model): awarded_by = models.CharField(max_length=30) user = models.ForeignKey(User, on_delete=models.CASCADE) badges = models.ForeignKey(Badge, on_delete=models.CASCADE) BadgeCategory refers to the category under which the badge falls, Badge refers to various badges. and reward contains all the various badges given to users. I am looking to find a query such that I get the following format of the output Username category 1 category 2 user 1 count(category 1) count(category 2) user 2 count(category 1) count(category 2) here count(category k) refers to the number of rewards that user has received having category k, If no reward is received it should be zero and username column should contain all the users. I have tried and reached to this query Reward.objects.all().values('user__username','badges__category__name') \ .order_by().annotate(Count('badges__category__name')) This gives the output having the users that have received at least one reward and only the category of which the badge has been received and the corresponding count of badges with that category, Let's say my database has 2 … -
Re-evaluate class OR make meta inner class lazy
I genuinely can't figure this out - been working on it for days. In django I have: globalvariablename = "tablename" class foo (models.Model): # Some attributes I don't care about class Meta: db_table = globalvariablename Now it's pretty obvious both foo and Meta will be evaluated once the class is imported / server is instantiated. Problem: I want db_table to be reassigned once I change globalvariablenamevalue My question: Is there anyway to make the Meta inner class lazy i.e. for it not to be evaluated until the model is used (e.g. when data is fetched from the database)? Alternatively, is there any way to re-evaluate Meta's db_table attribute once the globalvariablename has changed? Any help is appreciated. I'm literally pulling my hair out I've experimented lots with decorators i.e. for the Meta inner class to be added dynamically. This doesn't work because db_table is already assigned automatically as soon as the model is created and decorating it will just create additional duplicate values of db_table. -
Can Django serve different domains inside one single project?
I know about the sites framework but it requires to split the setting files and I'm not sure how to handle that in Apache properly. I'm also trying out all the request object attributes to determine what the host is like request.get_host() or request.site of the CurrentSiteMiddleware, I'm also trying the get_current_site method like this get_current_site(request) and I even address the .domain attribue itself. However I never reliably seem to be recognize the actual domain being called by the browser, like it always refers to the SITE_ID attribute of my settings.py It seems the sites framework is not so useful other than for model association. I'm not using subdomains, they're completely different domains. Can anybody please direct me to some proper and secure (not easily spoofable) procedures that I could deploy on a VPS to handle a few domains that will have a lot of content in common? -
How to pass ModelForm data from GET to POST?
On my app users can write reviews for novels. When a user clicks the Create Review button that is displayed on the page of every novel, he should be brought to a page were he can write a review for that given novel, also the reviewer is the current request.user, so I would like to set those two things for that review. Currently I've resolved this issue by doing this in novels.html: <form action="{% url 'create-review' %}" method="get"> <button type="submit" class="btn btn-primary">Write Review</button> <input type="hidden" name="novel_id" value="{{ novel.id }}"> </form> Now in my views.py file I have the following: class ReviewForm(ModelForm): class Meta: model = Review fields = ['reviewer', 'novel', 'content', 'rating'] widgets = { 'reviewer': HiddenInput(), 'novel': HiddenInput(), } def create_review(request): if request.method == "POST": form = ReviewForm(request.POST) if form.is_valid(): form.save() return redirect('index') else: review = Review( reviewer=request.user, novel=Novel.objects.get(pk=request.GET['novel_id']) ) form = ReviewForm(instance=review) return render( request, 'app/create_review.html', {'form': form} ) The data is passed along inside hidden input fields. This works just fine. However, what I'm wondering is if there is a better way to do it. As well as how to prevent the user from just going to app/create-review because then he would have not chosen a novel … -
Django field not appearing in validated data but it's in request
I have these serializers: class OneSerializer(serializers.ModelSerializer): class Meta: model = OneModel fields = ['time_column', 'event_column'] class TwoSerializer(serializers.ModelSerializer): survival_columns = OneSerializer(many=True, required=False) class Meta: model = UserFile fields = ['id', 'name', 'survival_columns'] Now in the create method I'm trying to retrieve survival_columns values from validated_data but it's not present! If I print the POST data the field and values appear correctly: def create(self, validated_data): print(self.context['request'].POST) # <QueryDict: {'name': ['Datos Clinicos de prueba.csv'], 'survival_columns': ['{"event_column":"Prueba","time_column":"prueba"}']}> print(validated_data) # {'name': 'Datos Clinicos de prueba.csv'} Why is the field survival_columns being filtered from the request? -
How to dynamically add django objects to a queryset
This is my models.py class Article(models.Model): title = models.CharField(max_length=100) #The title of the article # This is to count the number of users who have viewed the article viewed_user = models.ManyToManyField(User,related_name='viewed_user',blank=True) I'm trying to add the logic in the views.py in that when a user visits the particular article, if the user is not in the viewed_user list, that user is added there. This is what I have tried in the views.py article = get_object_or_4040(Article,id=id) if user in article.viewed_user.get_queryset(): print("User has already viewed the article") else: article.viewed_user.create(user=user) # THrows an error but I have gotten very many types of errors when I tried, update, create, set, append .... Any help would be appreciated THANKS.