Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: expected string or bytes-like object with django Q query
I'm trying to filter Event objects to only show events where the event.day is greater than or equal to today. However, I get the following error when I run it: TypeError: expected string or bytes-like object views.py today = datetime.now().day availability = Event.objects.filter(Q(day__gte=today)).order_by('-day') the day field in the Event model is a DateField. Any help would be greatly appreciated. Thanks! -
Django + PostgreSQL backup and restore on an EC2 instance
I have a simple monolithic architecture: A Django project hosted on an EC2 instance, talks to a PostgreSQL DB running on the same instance. I chose this architecture considering the traffic and cost. So, don't bash me on this one. :) For disaster recovery, I regularly dump my DB (a full dump pg_dump -U postgres fishercoder_db > fishercoder_dump.sql). At restoring, I cannot get Django and the restoring DB to talk nicely with each other: If I launch Django and run ./manage.py migrate first, and then restore the DB from the dump, it fails because Django has already created a bunch of internal tables after running ./manage.py migrate which have exactly the same name of in my dump; If I restore the DB from the dump first, then my Django app cannot stand up because of insufficientprivilege to run ./manage.py migrate, details asked here. My question is: Is my DR strategy reasonable? Any other more optimal ways? How can I get this approach to work: restore my site on a new EC2 instance with DB restored from a .sql dump. -
Displaying PPT in HTML web page
Currently creating an website using Python django framework using HTML and one of the features is file upload & view. It works fine with PDF documents, but when I try to view uploaded PPT documents, it always goes to download in chrome browser Few things I tried and didn't prefer are, 1) Using Embed PPT from Onedrive which supports already available documents. 2) Changing the PPT file into some other document format like PDF and viewing it directly from browser Please let me know how to view/display PPT file in HTML webpage without going through above complications. -
Django model history with foreign keys history tracking using django-simple-history
I have three models with historical records: class WifiUser(models.Model): .... wifiDevice = models.OneToOneField(WifiDevice, on_delete=models.CASCADE, default=None) wifiSim = models.OneToOneField(WifiSim, on_delete=models.CASCADE, default=None) history = HistoricalRecords() class WifiDevice(models.Model): .... history = HistoricalRecords() class WifiSim(models.Model): .... history = HistoricalRecords() I want to keep track of history with corresponding foreign key history records. But when accessing the history of Wifiuser I get the latest values of WifiDevice and WifiSim. I want the historical record of WifiDevice and WifiSim to point to that record of their one. Whats the best method to follow for this ? -
Sort db alphabetically with header in django
Writing website on django: i've got 1500 rows in DB Need to give those rows to frontend like: A Alice Andrew Ann B Bill Boris Brendan ... now in my views.py the for cycle goes around names and if the first letter of name is in the alphabet, that letter is added to my new alphabet: for name in names: if name[0] in alphabet: my_alphabet.append(name[0]) my_alphabet = sorted(list(set(my_alphabet))) Then I transfer my new alphabet and names to the html template: {% for letter in my_alphabet %} <span>{{ letter }}</span> {% for name in names %} {% if name.0 == letter %} <span>{{ name }}</span> {% endif %} {% endfor %} {% endfor %} That pages loads up to 10 seconds Maybe anyone's got a faster variant? Thanks for helping noob, sorry for wasting time! -
Django: Referencing inherited attributes from mixin
I have a long list of tuples used as model choices. They are currently class attributes in a model definition. I would like to move them into a mixin without affecting existing references across a legacy codebase. Here is what currently exists: class MyModel(models.Model): COLD = 1 WARM = 2 HOT = 3 FIRE = 4 STATUSES = ( (COLD, 'Cold'), (WARM, 'Warm'), (HOT, 'Hot'), (FIRE, 'Fire'), ) status = models.IntegerField(choices=STATUSES) Here is what I would like to do: class StatusMixin: COLD = 1 WARM = 2 HOT = 3 FIRE = 4 STATUSES = ( (COLD, 'Cold'), (WARM, 'Warm'), (HOT, 'Hot'), (FIRE, 'Fire'), ) class MyModel(StatusMixin, models.Model): status = models.IntegerField(choices=STATUSES) I'm trying to reference them: As part of the model inheriting them: my_model_instance = MyModel.objects.get(id=1) if my_model_instance.status == MyModel.FIRE: return As part of a model NOT inheriting them, but referencing the model that does: class OtherModel(models.Model): my_model_status = models.IntegerField(choices=MyModel.STATUSES) I am unable to satisfy both conditions. I'm sure there is a better way -- perhaps not a mixin? -
Implement python-social-auth with Django and Steam backend
not sure how to start this thread but i implemented the Python-Social-Auth to work with Github, i followed this tutorial and i got it working: https://simpleisbetterthancomplex.com/tutorial/2016/10/24/how-to-add-social-login-to-django.html So i decided ok why we don't make it with Steam and i found this: Proper way to implement python-social-auth with Django and Steam backend Bad news about it is that, i make everything i guess not sure if i have to do anything else, when i click login into Steam and i go to the https://steamcommunity.com/openid/login but when i get back to the website i get this at console: [19/Jun/2020 17:25:10] "GET /oauth/login/steam/ HTTP/1.1" 200 1230 [19/Jun/2020 17:25:52] "GET /oauth/complete/steam/?janrain_nonce=2020-06-19T21%3A25%3A10ZdgR4aL&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&openid.mode=id_res&openid.op_endpoint=https%3A%2F%2Fsteamcommunity.com%2Fopenid%2Flogin&openid.claimed_id=https%3A%2F%2Fsteamcommunity.com%2Fopenid%2Fid%2F76561198999680480&openid.identity=https%3A%2F%2Fsteamcommunity.com%2Fopenid%2Fid%2F76561198999680480&openid.return_to=http%3A%2F%2F127.0.0.1%3A8000%2Foauth%2Fcomplete%2Fsteam%2F%3Fjanrain_nonce%3D2020-06-19T21%253A25%253A10ZdgR4aL&openid.response_nonce=2020-06-19T21%3A25%3A50ZQ9%2F%2BHcdLB5lfPjbsYvmGpLCgSe0%3D&openid.assoc_handle=1234567890&openid.signed=signed%2Cop_endpoint%2Cclaimed_id%2Cidentity%2Creturn_to%2Cresponse_nonce%2Cassoc_handle&openid.sig=SLkLPpwAJyW8q9Ftp9bKlp8m%2Bys%3D HTTP/1.1" 302 0 [19/Jun/2020 17:25:52] "GET / HTTP/1.1" 302 0 [19/Jun/2020 17:25:52] "GET /login/?next=/ HTTP/1.1" 200 193 And never login, i go back and still says Login with steam or Github so i decided to check the database and i found that the entries are even added to it... Database Picture Any place where i can find help about this? Or anything that i might be missing? Thanks in advance! =) -
Django ListView filter objects
I have a simple structure Shop_list --> Product_list --> Product_detail I want to filter Product class object by slug field, but I see zero products. I think that the problem in get_queryset() views.py class HomePageView(ListView): model = Shop template_name = 'blog/shop_list.html' page_kwarg = 'shop' context_object_name = 'shops' class ProductListView(ListView): model = Product template_name = 'blog/product_list.html' page_kwarg = 'product' context_object_name = 'products' def get_queryset(self): pattern = str(self.request) pattern = pattern[1:] slug = self.model.shop return Product.objects.filter(shop__slug=pattern) def produt_detail(request, **kwargs): print(request) product = get_object_or_404(Product, pk=kwargs["pk"]) return render(request, 'blog/product_detail.html', {'product': product}) models.py class Shop(models.Model): title = models.CharField(max_length=200) image = models.ImageField(blank=True) slug = models.SlugField(null=False, default="Shop") def get_absolute_url(self): return reverse('product_list', kwargs={'slug': self.slug}) class Product(models.Model): shop = models.ForeignKey(Shop, on_delete=models.CASCADE, related_name="shop") title = models.CharField(max_length=200) price = models.CharField(max_length=200) period_start = models.DateTimeField(blank=True, null=True) period_end = models.DateTimeField(blank=True, null=True) def get_absolute_url(self): return reverse('product_detail', kwargs={'slug': self.shop.slug, 'pk': self.pk}) urls.py urlpatterns = [ path('', HomePageView.as_view(), name='shop_list'), path('<slug:slug>', ProductListView.as_view(), name='product_list'), path('<slug:slug>/<int:pk>/', views.produt_detail, name='product_detail'), ] product_list.html {% for product in products %} <a href="{% url 'product_detail' product.shop.slug product.shop.pk %}"> ... -
filter blogs by tags in Django
I'd like to render a view in Django with objects that have certain tags. Here's my model: class Tag(models.Model): """Model representing a tag.""" name = models.CharField(max_length=200) class Post(models.Model): """Model representing a post.""" title = models.CharField(max_length=200) # ManyToManyField used because tag can contain many posts. Posts can cover many tags. tag = models.ManyToManyField(Tag, related_name='tags', blank=True, default='', help_text='Select a tag for this post') after running migrations, I see three tables generated in my DB: blog_tag, blog_post and blog_post_tag blog_post table doesn't contain a column called tag, instead, this blog_post_tag holds all the mapping. What I'd like to achieve is to find all posts that have certain tags. I tried to use post_list = Post.objects.filter(tag__in=['AWS']), but this one throws Field 'id' expected a number but got 'AWS'. Any help on working this out would be greatly appreciated! -
Django slugfield changes unicode characters when saving and causes reverse no match error
I'm trying to create Unicode slugs with Django. The problem arises when it tries to save and resolve URLs with said slugs with Unicode characters in it. When I checked, Django seems to modify the characters when SlugField is used. This is my models.py: class Post(models.Model): title = models.CharField() slug = models.SlugField(unique=True, blank=True, allow_unicode=True) And I use slugify(slug, allow_unicode=True) to auto-generate slug from title. So to test this I used தமிழ் as title. Instead of a successful redirect to the URL /cats/test-cat/posts/தமிழ்/ Django showed NoReverseMatch exception with the following message. Reverse for 'post-detail' with arguments '('test-cat', 'zw93tz-தமழ')' not found. 1 pattern(s) tried: ['cats/(?P<cat_slug>[-a-zA-Z0-9_]+)/posts/(?P<post_slug>[-a-zA-Z0-9_]+)/$'] When I check the database, the title field has the right characters தமிழ் but the slug field has the modified characters தமழ. When I looked up for solutions, I found a workaround to use <str> instead of <slug> in urls.py. Why is this happening with <slug> and how to fix this? -
Send the logged user Profile Model to a CreateView form
what I am trying to accomplish is to send the "requester" model, using the logged-in user to a form ... Mainly the problem that I have is that the views.py "class CreateOrderView(CreateView)" does not have a parameter "request" , so I cannot get the request.user, and therefore get requester_obj and automatically select this requester_obj in the form field "requester", when entering this page. models.py Order: DEFAULT_REQUESTER_ID= 1 requester = models.ForeignKey(Profile, on_delete=models.CASCADE, default=DEFAULT_REQUESTER_ID, verbose_name="usuario") forms.py: class OrderCreateForm(BaseForm, forms.ModelForm): date = forms.DateField(label="Fecha" , widget=forms.DateInput(attrs={'type': 'date'})) class Meta: model = Order fields = ['requester','title' , 'date', ] views.py: @method_decorator(staff_member_required, name='dispatch') class CreateOrderView(CreateView): template_name = 'form.html' form_class = OrderCreateForm model = Order def get_success_url(self): self.new_object.refresh_from_db() return reverse('update_order', kwargs={'pk': self.new_object.id}) def form_valid(self, form): object = form.save() object.refresh_from_db() self.new_object = object return super().form_valid(form) I get the requester like this: @login_required def create(request): #return render(request, 'app_client/create.html') if request.method == 'POST': if request.POST['value'] and request.POST['products']: logged_user = request.user user_obj = get_object_or_404(User, username=logged_user) requestor_obj = get_object_or_404(Profile, user=user_obj) .... -
Why we can't host django app like laravel in apache server? [closed]
Got a question and curious if it's possible to do ... I configured apache server and it runs .py files and print html to request while visiting localhost JUSt like how .php file sendback response . we can easily copy laravel app in htdocs and it starts from index.php in laravel framework BUT things get messy with django , you have production server comes with django framework itself, and you need to connect with with some extension to apache. why we can't do the same with python django. I can write a semi framework inside htdocs with python that works like laravel and app starts from index.py etc etc ... just like laravel, Is this kind of thing related to framework itself or it is something technical and related to language itself ? -
Is this the right format of data send over ajax
This is how my data is going via ajax request. Is this is the right format? connection: 80 trans_data[0][name]: conditional_transformation trans_data[0][display_name]: Conditional Transformation trans_data[0][trans_text]: statement trans_data[0][trans_type]: condition Because my back-end system is looking for the keyword trans_data. But due to this structure the back-end is not able to process API. -
Get Serialize data of more than 1 models
i have 3 model class Camera(models.Model): CameraId = models.AutoField(primary_key=True, db_column='CameraId') CameraName = models.CharField(max_length=50) class DeviceType(models.Model): DeviceTypeId = models.AutoField(primary_key=True, db_column='DeviceTypeId') DeviceType = models.CharField(max_length=50) class Device(models.Model): DeviceId = models.AutoField(primary_key=True, db_column='DeviceId') DeviceName = models.CharField(max_length=50) CameraId = models.ForeignKey(Camera, on_delete=models.CASCADE, db_column='CameraId', related_name='cameras') DeviceTypeId = models.ForeignKey(DeviceType, on_delete=models.CASCADE, db_column='DeviceTypeId') i want result of Device serialize JSON data , related to Device { 'DeviceId' : DeviceId , 'DeviceName' : DeviceName , 'CameraId' : CameraId, 'CameraName': CameraName , 'DeviceTypeId' :DeviceTypeId , 'DeviceType' :DeviceType } How can i do it ? -
Django MaterializeCSS - working, but not sure the right way to set css and js?
I'm working on Django project with Materializecss design - Built a page with floating button for example. It's corrently working but I'm trying to understand better why it's actually working. I started using exactly the template from the website: https://materializecss.com/getting-started.html and updated from the CDN part in the page: <!--Import materialize.css--> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> And added at the bottom: <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> The floating button didn't work - After reading some posts, I use a suggestion to add the below, and it worked: Why the updated version of the files is not working? What's the right way to install it for production? Thanks a lot! The full HTML with the 'ADDED PART THAT MAKE IT WORK': <!DOCTYPE html> <html> <head> <!--Import Google Icon Font--> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!--Import materialize.css--> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> <!--Let browser know website is optimized for mobile--> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> </head> <body> <div class="fixed-action-btn"> <a href="#" class="btn-floating btn-large waves-effect waves-light red"><i class="material-icons">add</i></a> <ul> <li><a href="#" class="btn-floating btn-large blue"> <i class="large material-icons">filter_drama</i></a></li> <li><a href="#" class="btn-floating btn-large green"> <i class="large material-icons">insert_chart</i></a></li> </li> </ul> </div> <!--JavaScript at end of body for optimized loading--> <script type="text/javascript" src="js/materialize.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> ADDED PART THAT MAKE IT WORK: <!--JavaScript at end of body for … -
Django channels live chat save sent messages
So I have a Django app in which I used channels to implement live chat. My consumer looks like this: import json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] username = self.scope["user"] # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message, 'user': username.username } ) # Receive message from room group def chat_message(self, event): message = event['message'] user=event['user'] print(user) # Send message to WebSocket self.send(text_data=json.dumps({ 'message': message, 'user':user })) So I am looking for a way to save the sent messages (because currently they are lost on refresh). I have created a Messages model that has a CharField for the message text. I think I can save new messages if I do this in my chat_message function: new_message=Messages(text=message) new_nessage.save() My question is how do I preload the last 10 messages whenever a user gets connected to the chat? -
Django 301 Redirect configuration from old websites
I'm building a website builder in Django and customers are moving their old website to my service. I'm wondering how I could set up 301 redirects the right way so they dont lose backlinks / traffic from existing external links. My url conf is: domain.com/post-name Their old conf could be: domain.com/YYYY/MM/DD/post-name or domain.com/blog/post-name (and post-name might not be the same from old and new) So ideally, I'd like to build a scalable way for them to set up 301 redirects from a variety of different URL patterns. Would I create a catchall URL conf (which allows slashes) and check that first? Or check that if nothing was found at domain.com/post-name? I could add an old_url field to the Post model and check that after a post isn't found. -
Django pagination returning %20 whitespace in URL
I cannot figure out why Django pagination sometimes adds whitespace (%20) to the URL: https://example.com/accounts/?page=2%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20&q=%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20&ordering=-date_joined It happens if I click the Next or a specific page button so I assume it has to do with the way the pagination is written. More spoecifically I think it has to do with request.GET.items. Do context managers use request.GET.items? pagination: {% if page_obj.has_next %} <a class="btn btn-default btn-inactive mb-4 m-1" href="?page={{ page_obj.next_page_number }}{% for key, value in request.GET.items %} {% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}">Next</a> <a class="btn btn-default btn-inactive mb-4 m-1" href="?page={{ page_obj.paginator.num_pages }}{% for key, value in request.GET.items %} {% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}">Last</a> {% endif %} view: class AccountStatusListView(AccountSearchMixin, ListView): model = Employee template_name = 'employees/account_list.html' paginate_by = 15 def get_ordering(self, *args, **kwargs): ordering = self.request.GET.get('ordering', '-is_active') return ordering def get_queryset(self, *args, **kwargs): queryset = super(AccountStatusListView, self).get_queryset() queryset = queryset.filter(Q( supervisor__exact=self.request.user)) | queryset.filter(Q( supervisor__isnull=False)) | queryset.filter(Q( is_active__exact=False)) ordering = self.get_ordering() if ordering and isinstance(ordering, str): ordering = (ordering,) queryset = queryset.order_by(*ordering) return queryset Anybody have any idea what is going on here? -
GET without unrequired fields in Django
Hope the title makes sense. I want to be able to search the Yelp API using a location (required) and a name (not required). Right now you are allowed to leave the name field blank but it will still use that in a search, therefore returning nothing no matter what. base.html <form action="{% url 'venue_list' %}"> <!-- NOT required --> {% render_field search_form.search_name.label %}: {% render_field search_form.search_name class="form-control" %} <!-- required --> {% render_field search_form.search_location.label %}: {% render_field search_form.search_location class="form-control" %} <input type='submit' value='SEARCH'> </form> yelp_api.py def get_name(location, term=None): url = 'https://api.yelp.com/v3/businesses/search' if term != None: params = { 'location': f'{location}', 'term': f'{term}' } else: params = { 'location': f'{location}' } headers = {'Authorization': f'Bearer {YELP_API_KEY}'} *etc etc* forms.py class SearchForm(forms.Form): search_name = forms.CharField(required=False, label='Name') search_location = forms.CharField(required=True, label='City, State, or Zip Code') views_venues.py def venue_list(request): search_location = request.GET.get('zip_code') search_name = request.GET.get('name') if not Venue.objects.filter(zip_code=search_location).exists(): venues = yelp_api.get_name(search_location) venues = Venue.objects.filter(zip_code=search_location).order_by('name') else: venues = Venue.objects.filter(zip_code=search_location).order_by('name') return render(request, 'restroom_rater/venue_list.html', { 'venues': venues, 'search_location': search_location}) views_venues.py i know is only set up to search for the location because that's how I originally had it set up. Getting stuck trying to do just location or location AND name. Let me know if there's … -
How Can make PyCharm's autocomplete work on django?
I am using pycharm community , I make test project on django and in template I make degree.html file. I have the following code in degree.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>welcome to degree site of {{student_id}}</title> </head> <body> {%for item in degree%} <h4> {{item.student_dgree}} </h4> <h4> {{item.student_id}} </h4> {%endfor%} </body> </html> I can't complete instruction like "for , endfor , .. etc" I install django from cmd and from pycharm's terminal too using pip. and from File -> Settings -> Project Interpreter I add django Package and install it help please ! -
Django upload image for current user for him cars
I am trying to make a uploading form for images with a choice of a car in the field, but in the field there should be only cars of the current dealer I have the following models: class Photo(BaseDateAuditModel): image = models.ImageField(upload_to='photos/') position = models.SmallIntegerField(default=1, validators=[MinValueValidator(limit_value=1)]) car = models.ForeignKey('cars.Car', on_delete=models.CASCADE, related_name='photos') class Dealer(User): city = models.ForeignKey('City', on_delete=models.SET_NULL, null=True, blank=False) class Car(BaseDateAuditModel): properties = models.ManyToManyField(Property) objects = CarManager.from_queryset(CarQuerySet)() views = models.PositiveIntegerField(default=0, editable=False) slug = models.SlugField(max_length=75) number = models.CharField(max_length=16, unique=True) dealer = models.ForeignKey("dealers.Dealer", on_delete=models.CASCADE, related_name='cars', null=True, blank=False) model = models.ForeignKey('CarModel', on_delete=models.SET_NULL, null=True, blank=False) color = models.ForeignKey('Color', on_delete=models.SET_NULL, null=True, blank=False) Form for upload images: class ImageForm(forms.ModelForm): class Meta: model = Photo fields = ['image', 'car'] widgets = { 'image': forms.ClearableFileInput(attrs={'multiple': True}), } View: class UpdateImageView(FormView): model = Photo form_class = ImageForm template_name = 'image-update.html' def get_success_url(self): return reverse('cars:cars-list') def form_valid(self, form): form.save() return super().form_valid(form) # 1st way, get list all car, not only for current user def get_queryset(self): ''' return a list of cars of the current user for example: my current dealer(user) have one car and this method return: Car.objects.filter(id__in=car_list) == <CarQuerySet [<Car: Audi >]> ''' user = self.request.user car_list = Dealer.objects.filter(username=user).values_list('cars', flat=True) return Car.objects.filter(id__in=car_list) # # def post(self, request, *args, **kwargs): … -
How to play an audio file through http response in Django
I want to know how to play an audio file in the browser How to play an audio file in the browser? -
Is it possible to target the single object's attributes among the objects QuerySet in Django ListView?
I want to get the attributes just for a single object in the object_list, but there is no way for me to access it as the contexts were only objects_list. I would like to access the attribute/field in the Post model(eg. Author/likes) in views.py in order to set an if statements and return the context e.g.: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) post = context['post'] if post.likes.filter(id=self.request.user.id).exists(): context['is_liked'] = True return context -
Serializing a block of text django rest-framework and displaying paragraphs with react
I am creating a blog and using djangorestframework as my backend and react for my frontend. When I serialize my data, I lose the formatting for my blog enteries (which are written in paragraphs). Is there a way to fix this. So: Blog Post This is my blog post, and this is my formatting. My second paragraph. becomes. [{ "title": "blog post", content: "This is my blog post, and this is my formatting My second paragraph." } ] When i pass it through my react it remains This is my blog post, and this is my formatting My second paragraph. -
Variables are not rendenring [DJANGO]
I m making a blog site.And I have been trying to render drom a model RecentPosts objects rpost1 ..etc in my template blogs-base.html which is my blogs details page. But it is not rendenring. Any solution?? views.py from django.http import HttpResponse from django.shortcuts import render from blog.models import Post from django.contrib import messages from django.views.generic import ListView , DetailView from .models import Post , RecentPosts , Comment ,Contact ,Populars from datetime import datetime from .forms import CommentForm def index(request): return render(request, 'index.html') def path(request): return render(request, 'blog.html') def cv(request): return render(request, 'cv.html') class HomeView(ListView): model = Post template_name = 'listview.html' class ArticleDetailView(DetailView): model = Post template_name = 'base2.html' def rpost(request): template_name = "blogs-base.html" rpost = RecentPosts.objects.all() context = {'rpost' : 'rpost'} return render(request ,template_name,context) This is url portion. urls.py from django.urls import path from . import views from .views import HomeView ,ArticleDetailView ,contact ,Comment_page,popular urlpatterns = [ path('', views.index, name='index'), path('index.html', views.index, name='index'), path('cv.html', views.cv, name='cv'), path('blogs/',views.HomeView.as_view(),name="blogs"), path('blogs/<slug:slug>',ArticleDetailView.as_view(),name='base2'), path('contact/', views.contact, name='contact'), path('contact.html/', views.contact, name='contact'), path('comment.html/', views.Comment_page, name='comment'), path('popular', views.popular, name='popular'), ] This is the model portion. models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse from django.utils.timezone import now # Create your models here. class Post(models.Model): …