Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django:How to return nowhere?
(sorry for my bad english) hello mans.i have a such view in django: if request.user.is_authenticated: favelan = get_object_or_404(elan,id = id) isfav = True if favelan.favorit.filter(id = request.user.id).exists(): favelan.favorit.remove(request.user) messages.success(request,'Elan Uluzlulardan Silindi!') isfav = False return redirect("/",{'isfav':isfav}) else: favelan.favorit.add(request.user) messages.success(request,'Elan Uluzlulara Elave Olundu!') isfav = True return redirect("/",{'isfav':isfav}) return redirect('/hesablar/qeydiyyat') i want this view redirect user nowhere.how i do this?i tried: reqabspath = request.path return redirect(reqabspath,{'isfav':isfav}) but its not working.i want redirect user nowhere.please help me.thanks now. -
How to pause and stop celery task from django template
I am working on a django application that uses celery to run tasks asynchronously. Right now a user can submit a form from the webpage to start a celery task. But there is no way to pause or stop the task on the click of a button inside a django template. this is my code so far celery task @shared_task def get_website(website): website_list = return_website_list(website) return website_list In the above task I am calling a return_website_list() function that scrapes the required website and returns a list of links from the website. output.html template <div class="container"> <button class="pause_btn" type="button">Pause task</button> <button class="resume_btn" type="button">Resume task</button> <button class="stop_btn" type="button">Stop task</button> </div> I want the ability to pause the task indefinitely when the pause button is clicked and resume the task when the resume button is clicked or the ability to stop the task completely when the stop button is clicked. views.py def index(request): if request.method == 'POST': website = request.POST.get('website-name') get_website.delay(website) return redirect('output') return render(request, 'index.html') I searched online, like these link1, link2, link3. But these links did not help me achieve what I am trying to do. Thanks in advance -
ModuleNotFoundError: No module named 'articles'
I have Django code to backend. But it's not starting because of this error ModuleNotFoundError: No module named 'articles' StackOverflow people says that you don't have this folder or wrote it wrong in 2 urls.py documents. Here is the structure of my 1st project. Can't you fuys exlain me why this isn;t working? -
Changing the Link Preview image from a django site
I wanted to share the link of my article on social media but the link preview is showing my image(author's image) instead of the featured image of the post. I've already tried SEO meta tags. The image I want to show is this. I don't know what am I doing wrong. How do I change link preview thumbnail? models.py ..... ... class Post(ModelMeta, models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() image_file = models.ImageField(upload_to='media', null=True, blank=True) image_url = models.URLField(null=True, blank=True) category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE, null=True) published_date = models.DateTimeField(blank=True, default=timezone.now ,null=True) _metadata = { 'title': 'title', 'image': 'get_meta_image', } def get_meta_image(self): if self.image_file: self.image = self.image_file return self.image.url else: self.image = self.image_url return self.image.url class Meta: verbose_name = "Post" verbose_name_plural = "Posts" ordering = ('-published_date',) def get_absolute_url(self): return reverse("post_detail",kwargs={'pk':self.pk}) def __str__(self): return self.title ..... ... views.py ..... ... class PostDetailView(DetailView): model = Post template_name = "blog/post_detail.html" def post(self,request,*args,**kwargs): self.object = self.get_object() context = self.get_context_data() if request.method == 'POST': form = SubscriberForm(request.POST) if context["form"].is_valid(): context["email"] = request.POST.get('email') form.save() messages.success(request, 'Thank you for subscribing') return redirect('/') else: form = SubscriberForm() def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super(PostDetailView, self).get_context_data(**kwargs) # Add … -
Django form won't render (modelForm)
I have an existing site, and I'm trying to render a form to it I tried looping trough the form and rendering it field by field, but no luck. I think i might screwed up something in my views, im a beginner to django HTML: {%block wform%} <form method="POST" class="form"> {% csrf_token %} {{ form.as_p }} <div class="form__group"> {%if user.is_authenticated%} <input type="submit" class="submit" value="Submit Your Data"> {%else%} <a href="{% url 'login' %}" class="submit">Submit Your Data</a> {%endif%} </div> </form> {%endblock wform%} Forms.py from django.forms import ModelForm from users.models import Profile class WeightForm(ModelForm): class Meta: model = Profile fields = ['weight','height','goal'] Views.py from django.shortcuts import render from django.contrib import messages from users import models from users.models import Profile from .forms import WeightForm # Create your views here. def home(request): return render(request, 'Landing/index.html') def formsave(request): form = WeightForm() return render(request, 'Landing/index.html', {'form': form}) -
Django: Which method or function should be overriden to apply markdown2 to generic view rendering?
I am able to apply Markdown2 to convert marked down text from the database to HTML that is rendered on a template html page. relevant code : views.py page = entry.content page_converted = markdown2.Markdown().convert(page) context = {'mdentry': page_converted, "subject":subject} return render(request, "wikiencyc/md_entry.html", context) md_entry.html {% block content %} {{ mdentry|safe }} {% endblock %} The problem is how do I apply the Markdown2 conversion to a generic DetailView where all the boilerplate python code is in the django server code. I understand that I would have to find the relevant method or function within the django server code and override it as a local method in the generic view to accomplish the Markdown2 conversion. Right now, the detailview class is just: class EntryDetailView(generic.DetailView): model = Entry slug_field = 'subject' slug_url_kwarg = 'subject' The rest of the functionality to render the object to a view is embedded in the django server code. I need access to the relevant code to override it as local method to get the Markdown2 conversion. Which method of which class would it be. Or, can the markdown2 conversion be done directly on the template somehow. Any help greatly appreciated. -
How to open the edit section without refreshing the page for each post in Django Javascript?
this is my html template: <div class="posts"> <h3> <a href ="{% url 'profile' p.user.id %}"> {{p.user}}: </a> </h3> <p>{{p.timestamp}}</p> <br> <p><i class="fas fa-heart"></i> {{ p.likes.count }}</p> <p style="text-align: center;"> {{ p.post }} </p> {% if p.user.id == user.id %} <button class="btn btn-primary edit" style="display: inline;">Edit</button><hr></div> <div id="editsec"> <textarea rows=6 cols=100 style="opacity: 0.7;">{{p.post}} </textarea> <form action=""><button class="btn btn-success">Save</button></form> </div> {% endif %} {% endfor %} Now in css I hide the editsec, so only if user clicks on edit button, it will display editsec div and hide the posts div. Here is Javascript code: document.addEventListener('DOMContentLoaded', function() { var edit = document.getElementsByClassName('edit') for (var i = 0 ; i < edit.length; i++) { edit[i].addEventListener('click', () => { document.getElementById('editsec').style.display = "block"; document.querySelector('.posts').style.display = "none"; }); } }); Now if I have two post in home page, if I click on second post's edit button, it is still displaying the first post's editsec div. I tried to make this editsec a class and did this : document.addEventListener('DOMContentLoaded', function() { var edit = document.getElementsByClassName('edit') var editsec = document.getElementsByClassname('editsec') for (var i = 0 ; i < edit.length; i++) { edit[i].addEventListener('click', () => { for (var a = 0 ; a < edit.length; a++) { editsec[a].style.display … -
Jquery: Select all check boxes when 'select all' is checked
I have a form that prints a out menu items from each category. I want to have a select all checkbox over each category such that when clicked, all checkboxes of that category are selected - this part works with my script. Issue: Sometimes some check boxes are not checked by default e.g. no data in database - in that case the select all checkbox should not be checked when page is rendered (it should only checked if all its child check boxes are checked). Current partial implementation (checked is true for select all even if some of its some menu items are not checked?!): <form method="post"> {% for main_name, items in default_menu %} <table class="report"> <br /> <tr> <th colspan='2'></th> <th colspan='2'></th> <th colspan='2'></th> </tr> <tr> <th colspan='2'>{{main_name}}</th> <th colspan='2'>Available</th> <th colspan='2'><input id="{{main_name}}" class="all" type="checkbox" checked="true" /> </th> </tr> {% for url, item_name, selected in items %} {% if selected %} <tr> <td colspan='2'>{{item_name}}</td> <td colspan='2'><input name="{{main_name}},{{item_name}}" class="{{main_name}}-item" type="checkbox" checked="true"/></td> </tr> {% else %} <tr> <td colspan='2'>{{item_name}}</td> <td colspan='2'><input name="{{main_name}},{{item_name}}" class="{{main_name}}-item" type="checkbox" /></td> </tr> {% endif %} {% endfor %} </table> {% endfor %} <input type="submit" value="Save Setting" style="margin-top:20px; margin-left:0;"> </form> <script type="text/javascript"> checked = true; $(".all").click(function() { checked … -
Can Django Rest Framework and Channels be used to create Real-Time Messaging application?
I am a college student with a team 7 other developers like me. We and to develop a real time messaging mobile app (eg: WhatsApp, Messenger) etc. We have started development in React Native for the frontend and Django Rest Framework for the backend. My question is, can it be done? - If yes, then how should we go about it ? - If no, then what can be a possible alternatives and technologies ? the main issue I am facing is to implement real time web-sockets in Django rest framework. -
How to use stored procedures with Django backend?
I have created a stored procedure in SSMS for the query SELECT * FROM TABLE and now I want to create a Django API and test it. What is the entire procedure? My script from SQL Stored Procedure: USE [test] GO /****** Object: StoredProcedure [dbo].[spGetAll] ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: <Author,,Name> -- Create date: <Create Date,,> -- Description: <Description,,> -- ============================================= CREATE PROCEDURE [dbo].[spGetAll] AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; -- Insert statements for procedure here SELECT * from app_comment END GO -
Embedding QuickChart.io image in HTML from Django app
I'm very new to HTML and web development so forgive me is this is an easy fix. QuickChart.io provides an image after calling the API. I've created a Django application that creates a custom URL to call QuickChart in my view file but struggling to have it appear when loading the page. My HTML is the following: {% block content %} <img src=quickchart_url> <p>{{ quickchart_url }}</p> {% endblock %} The site loads as follows: I can copy and paste the URL in a browser and it displays as intended. Just trying to figure out how I can have this appear from HTML. -
Django project failed to start syntax error '<frozen importlib._bootstrap>'
i just wanted to start project in django, but it failed with this code can anyone explain me what's wrong here, i am newbie in django pls help. And if you ask a can share with code that contains in documents. I've edited standard files and created some new files like urls.py and many inserted code for starting project. but it fails everytime when i start Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Bakhtyar\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\Bakhtyar\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Bakhtyar\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Bakhtyar\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\Bakhtyar\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = checks.run_checks( File "C:\Users\Bakhtyar\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Bakhtyar\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\Bakhtyar\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Bakhtyar\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 408, in check for pattern in self.url_patterns: File "C:\Users\Bakhtyar\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Bakhtyar\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Bakhtyar\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Bakhtyar\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 582, in urlconf_module return import_module(self.urlconf_name) … -
How does Fargate send both uWSGI and Django logs from the container to Cloudwatch
I have Django running behind uWSGI in a docker container in AWS Fargate. The container logs are sent to Cloudwatch. In my setup, I would be okay if both uWSGI and Django log to stdout/stderr and the logs are getting mixed. Pasting my config below. This is my entrypoint.sh: #!/bin/bash python manage.py collectstatic --noinput python /code/manage.py migrate --noinput exec uwsgi --show-config --log-master I can see proper log output from Django for collectstatic and the migrate call. DEBUG 2020-09-06 07:39:38,589 retryhandler 6 139721333720896 No retry needed. These are easy to recognize, because they start with the log level DEBUG. As soon as a the uWSGI process starts, I stop seeing any log events from Django. The only thing I see are uWSGI log events like: [pid: 13|app: 0|req: 2/1] 10.0.2.249 () {30 vars in 352 bytes} [Sun Sep 6 07:39:46 2020] GET / => generated 3877 bytes in 444 msecs (HTTP/1.1 200) 4 headers in 128 bytes (1 switches on core 1) In the Dockerfile I am setting 3 additional uWSGI related environment variables: ENV UWSGI_WSGI_FILE=sanctionsio/wsgi.py ENV UWSGI_HTTP=:8000 UWSGI_MASTER=1 UWSGI_HTTP_AUTO_CHUNKED=1 UWSGI_HTTP_KEEPALIVE=1 UWSGI_LAZY_APPS=1 UWSGI_WSGI_ENV_BEHAVIOR=holy ENV UWSGI_WORKERS=2 UWSGI_THREADS=4 Django logging is set up like this: LOGGING_LEVEL = 'DEBUG' LOGGING = { 'version': 1, … -
how to ajaxify the post uploaded in django
I have already created posts. Users can post their own posts with images and can update and delete them. But now i want to list the already posted posts of the user with ajax . But i don't how to do that with the images. here's the post of user in my template {% for object in object_list %} <div class="post-card" > <p> <img class="rounded-circle profile-image" src="{{ object.author.profile.image.url }}"> <span class="auth-span"><b>{{ object.author }} </b><i class="fa fa-check-circle"></i> </span> <span class="date-span">{{ object.date_created|timesince }} ago</span> </p> <p><a href="{% url 'detail' object.id %}" class="title">{{ object.title }}</a></p> <div> {% if object.Image %} <p><a href="{% url 'detail' object.id %}"><img src="{{ object.Image.url }}" class="img-fluid" alt="Responsive image" ></a></p> {% endif %} </div> <div class="icon-div" > <p class="icon" style="mt"> <i class="fa fa-comments"></i> <i class="fa fa-heart" ></i> <i class="fa fa-share-square"></i> <i class="fa fa-eye"></i> </p> </div> </div> {% empty %} {% if request.GET.q %} <p style="color: var(--text-color);margin-top: 20px;margin-left: 250px;">NO tweets found</p> {% else %} <p>NO tweets yet.</p> {% endif %} {% endfor %}` So how do i show these posts with jquery for ajax? -
Push Notifications with Angular and Django Rest Framework
I want to build a Progressive Web App with Angular in the Frontend and Django/Django Rest Framework in the backend (PostgreSQL as an RDBMS). I want to have Push Notifications in my system, for example, I have a table of 'payments' in my DB, and one day before the 'due_date' of a 'payment' I want to send a push notification to the User. Can you recommend me some libraries, third-party Message Brokers maybe that would go well with Angular and DRF. I am not very familiar with Angular, but I will mostly handle the backend stuff. -
Django3x RuntimeError:
I am learning Django 3x and when I try to add a path in config/urls.html "path( cheeses/', include('everycheese.cheeses.urls', namespace='cheeses'), ),", it throws an runtimeerror, "RuntimeError: Model class everycheese.cheeses.models.Cheese doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS." I searched for solutions but found the existing answers cannot fix it. Could anyone help me? Thank you. ./config/urls.html ... urlpatterns = [ path( "", TemplateView.as_view(template_name="pages/home.html"), name="home", ), path( "about/", TemplateView.as_view(template_name="pages/about.html"), name="about", ), # Django Admin, use {% url 'admin:index' %} path(settings.ADMIN_URL, admin.site.urls), # User management path( "users/", include("everycheese.users.urls", namespace="users"), ), path("accounts/", include("allauth.urls")), # Your stuff: custom urls includes go here path( 'cheeses/', include('everycheese.cheeses.urls', namespace='cheeses'), ), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ... ./cheeses/models.py from django.db import models from autoslug import AutoSlugField from model_utils.models import TimeStampedModel class Cheese(TimeStampedModel): class Firmness(models.TextChoices): UNSPECIFIED = "unspecified", "Unspecified" SOFT = "soft", "Soft" SEMI_SOFT = "semi-soft", "Semi-Soft" SEMI_HARD = "semi-hard", "Semi-Hard" HARD = "hard", "Hard" name = models.CharField("Name of Cheese", max_length=255) slug = AutoSlugField("Cheese Address", unique=True, always_update=False, populate_from="name") description = models.TextField("Description", blank=True) firmness = models.CharField("Firmness", max_length=20, choices=Firmness.choices, default=Firmness.UNSPECIFIED) def __str__(self): return self.name -
Get value from intermediate table
I have 2 tables "Sample" and another one "Test", with a pivot table (intermediate) "SampleTest" that has the ForeignKeys plus an extra field "result". I made a view.py where I can get the "Sample" and "Test" data: def imprimir(request, id): sample = Sample.objects.get(pk=id) tests = sample.tests.all() return render(request, 'protocolo.html', { 'sample': sample, 'tests': tests, }) But I would also like to take the value "result" from my intermediate table, and that this value comes in the variable "tests". How can I do this? From already thank you very much -
How to change the select options based on the radio check?
Here I have div column for subject. There is a select option and I want to change this options based on the user check either general or reserve. If general Select Listing option and if reserve lisitng detail options should be displayed. At the first general option will be checked so Select Lisiting option should be displayed by default. If user clicks the reservation then the Listing Detail option should be displayed. How can I do it ? <input type="radio" id="general" value="general" onclick="javascript:chooseTableRows();" name="option" >General</label> <label><input id="reserve" value="reserve" type="radio" name="option" onclick="javascript:chooseTableRows();">Reservation</label> <div class="form-group row" id="sub" style="display:none;"> <label class="col-sm-2 col-form-label">Subject:</label> <div class="col-sm-10"> <select class="js-example-basic-single" name="subject" required="" style="width: 250px;"> <option selected value="">Listing Detail</option>{{event}} {% for listing in listing_details %} <option value="{{listing.listing.nickname}}">{{listing.listing.nickname|truncatechars:20}}</option> {% endfor %} </select> </div> # want to replace this select upon reserve option checked <select class="js-example-basic-single" name="subject" required="" style="width: 250px;"> <option selected value="" id="sub1">Select Listing</option> {% for listing in listings %} <option value="{{listing}}">{{listing}}</option> {% endfor %} </select> script <script type="text/javascript"> function chooseTableRows() { if (document.getElementById('reserve').checked) { document.getElementById('sub1').style.display = 'block'; document.getElementById('sub').style.display = 'none'; } else { document.getElementById('sub').style.display = 'block'; document.getElementById('sub1').style.display = 'none'; } } </script> -
Django custom url using rest framework
I have a model ... class Person(models.Model): first_name = models.CharField(max_length=30), last_name = models.CharField(max_length=30) I'm using React on the frontend and using json to deal with my data. So in my urls.py file I'm using drf-extensions I'm using it because it allows me to do some nested routing but I am having trouble now trying to router correctly if I want all people by name from my database. For instance, I have a viewset class PersonView(viewsets.ModelViewSet): serializer_class = PersonSerialzer queryset = Person.objects.all() And I am getting all the data back from my table but I want to have this and also be able to hit an endpoint where I can get back all rows with the same first name. I'm not sure how to do this. -
Add multiple products to an order - Django
I'm trying to create an inventory management system. I'm having problems figuring out how to add multiple inventory items into my order from a table. I want to achieve this by selecting the item by the checkbox and also adding the quantity. html <form method="POST" action=""> {% csrf_token %} {% for field in form %} <div class="form-group row"> <Label for="id_{{ field.name }}" class="col-2 col-form-label">{{ field.label }}</Label> <div class="col-10"> {{ field }} </div> </div> {% endfor %} <table class="table table-striped"> <tbody> {% for item in Inventory %} <tr> <td> <input type="checkbox" name="itemCheck" value="{{ item.pk }} "></td> <td> <input name="itemQuantity"> </td> <td> {{ item.name }} </td> <td> {{ item.quantity }} </td> <td> <span class="badge badge-pill badge-success">{{item.status}}</span></td> <td> ${{ item.sale_price }} </td> </td> </tr> {% endfor %} </tbody> </table> views.py def create_order(request): order_form = OrderForm(request.POST) if request.method == 'POST': if formset.is_valid(): total = 0 order = Orders(total=total) order.save() order_form.save() selected_items = request.POST.getlist('itemCheck') print(selected_items) # This returns the primary keys of the selected items context = {"form": order_form, "Inventory": Inventory.objects.all()} return render(request, 'create_order.html', context) models class Inventory(models.Model): name = models.CharField(max_length=128, blank=False) ... def __str__(self): return f"{self.id} - {self.name}" class Orders(models.Model): studio = models.CharField(max_length=64) status = models.CharField(max_length=64, default="warehouse", blank=False) total = models.DecimalField(max_digits=10, decimal_places=2) class OrderEquipment(models.Model): … -
OperationalError at /admin/core/order/ no such column: core_order.shop_name_id
i want to use shop table as foreign key to filter items and order in the adminview but got that error models class Shop(models.Model): shop_name = models.CharField(max_length=100) class Item(models.Model): title = models.CharField(max_length=100) shop_name = models.ForeignKey(Shop, on_delete=models.CASCADE) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField() stock_no = models.CharField(max_length=10) description_short = models.CharField(max_length=50) description_long = models.TextField() image = models.ImageField() image1 = models.ImageField(blank=True, null=True) image2 = models.ImageField(blank=True, null=True) is_active = models.BooleanField(default=True) class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) shop_name = models.ForeignKey(Shop, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) payment_received = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) in admin i defined the the model shop admin.py admin.site.register(Shop) -
Created A Sitemap But Google Couldn't Fetch Error
In Django, I've created a sitemap for my project. I didn't used built in django sitemap framework. I created a view and template and point it from urls.py. When I open it in explorer sitemap works fine. But when I add my sitemap to my searh console google give me couldn't fetch error. Couldn't figure out what is the problem. Any idea? My View: class SitemapPost(ListView): model = Movies ordering = ['-pk'] template_name = "front/sitemap-post.xml" content_type='application/xml' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) today = datetime.now() context['today'] = datetime.now() return context Urls: path('sitemap-post.xml', SitemapPost.as_view(),name='sitemap-post'), template: <?xml version="1.0" encoding="UTF-8"?> <urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd http://www.google.com/schemas/sitemap-image/1.1 http://www.google.com/schemas/sitemap-image/1.1/sitemap-image.xsd" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> {% for object in object_list %} <url> <loc>https://{{request.get_host}}{{ object.get_absolute_url }}</loc> <lastmod>{{today|date:"Y-m-d"}}</lastmod> <changefreq>daily</changefreq> <priority>0.9</priority> </url> {% endfor %} </urlset> and here is my sitemap file: link -
FormSet for a child class only
class Parent(Form): field1 = forms.FloatField(.....) field2 = forms.IntegerField(.....) field3 = forms.IntegerField(.....) field4 = forms.CharField(.....) class Child(Parent): field5 = forms.CharField(.....) I'm trying to have a formset to repeat the "Child" class field without repeating the "Parent" class fields I've tried ChildFormSet = formset_factory(Child, extra=10) but this will repeat the parent as well Any ideas? -
Not able to add Emoji's as comment "OperationalError :Incorrect string value: '\\xF0\\x9F\\xA5\\xB0' for column 'content' at row 1"
when I tried to add emoji's i'm getting this error did not workout even CharField getting the same error. models.py class Comment(models.Model): post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE) content = models.TextField(max_length=500, blank=False) author = models.ForeignKey(User, on_delete=models.CASCADE) date_created = models.DateTimeField(default=timezone.now) def __str__(self): return self.content def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.post.pk}) # returns a string to the post detail that uses the pk of the comment instance. post. pk to link to the correct detail page ie. /post/ def save(self, *args, **kwargs): super(Comment, self).save(*args, **kwargs) n = 4 truncatewords = Truncator(self.content).words(n) notify.send(self.author, recipient=self.post.author, verb='commented "' + truncatewords + '" on your post!', action_object=self.post, description='comment', target=self) -
How to attach an image in mail using django
I tried sending mail using Django. It worked well when I sent simple mail. But how can I add attachments(image) to my mail?