Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I save all scrapped data one by one into the database
I wrote a script in a py file to scrapped data from website https://www.dataquest.io/blog/ (just for the learning purpose) that is working perfectly fine. Scrapping all data as I want. I introduce that script file in a Django app as a ScrapperApp. I want to store all the scraped data into the database. After running the server and executing the script. The webpage is simply loading as it is. But database showing an only single instance of scraped data from the website. scrape.py from bs4 import BeautifulSoup import requests src = 'https://www.dataquest.io/blog/' source = requests.get(src).text soup = BeautifulSoup(source, 'lxml') total = 0 for article in soup.find('section', class_='bSe right').find_all('article'): try: headline = article.find('h2', class_='entry-title').text print('Heading : ', headline) summary = article.find('p').text print('Summary: ',summary) category = article.find('div', class_='category').find('span').text print(category) blog_link = article.find('div', class_='awr').find('a', class_='psb')['href'] print(blog_link) total += 1 except exception as e: pass print() print(total) models.py from django.db import models class BlogCards(models.Model): headline = models.CharField(max_length=500, blank=True) category = models.CharField(max_length=300, blank=True) summary = models.TextField(blank=True) link = models.URLField(blank=True) total_blogs = models.IntegerField() def __str__(self): return self.headline views.py of Django ScrapperApp from django.shortcuts import render from bs4 import BeautifulSoup import requests from .models import BlogCards import logging def ScrapperView(request): src = 'https://www.dataquest.io/blog/' source = requests.get(src).text soup … -
received posted json in djanog ModelViewSet
I am trying to get the information from a post with a json. I have used get_queryset to get parameters from a get url. That works without problems. But I want to post a json of data instead. I thought the data was in the body. But it might be that the get_queryset is not activated on a post. class NNTradesView(viewsets.ModelViewSet): serializer_class = NNTradesSerializer # queryset = NNTrades.objects.filter( # symbol__contains='VOLV B').order_by('new_date') def get_queryset(self): symbol = self.request.body print(symbol) queryset = NNTrades.objects.filter( symbol__contains=symbol).order_by('new_date') logging.warning('queryset', symbol) return queryset @action(detail=True, methods=['post']) def test(self, request, pk=None): print("something") -
how to access django models with script outside of the project
I have two projects. The new one bases on Django and the old one based on PHP. Both are alive. I want to synchronize all info between these projects. I have a python script which parse all info from the PHP project but I can't load it to the Django project. The only way I found to solve the problem is to connect to sqllite DB of the django project from my python script. But I feel that this solution is not the best& Is there a way to write smth like this in my python script: from .models import MyModel for (f1, f2, f3) in parse_results: result = MyModel.objects.create(field1=f1, field2=f2, field3=f3) For now when i try to import MyModel i see ModuleNotFoundError: No module named '__main__.models'; '__main__' is not a package -
Django 2 media returns error 404 (top level media folder)
Running Django 2.1.5 with Python 3.7.2 32-bit, Win10 localhost, no nginx etc. Cloned the repo https://github.com/axelpale/minimal-django-file-upload-example.git Can upload files and they appear as a url link in the db and as a list item on the page but the images/files do not display on the page and return 404 in the console. Error returned: GET http://127.0.0.1:8001/media/documents/2019/04/07/image.jpg 404 (Not Found) I can see the file at that location in explorer. The code is exactly as per the repo with the addition of the following: list.html line 14 <li><img src="{{ document.docfile.url }}" height="60px"></li> and urls.py from django.conf import settings from django.conf.urls.static import static urlpatterns = static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + [ path('', views.list, name='list')] I have followed the documentation as far as I can and looked at other SO post that suggest the static pattern should go first. It should be noted that the media folder is at the top level of the directory. for_django_2-0 -myproject --myproject --media --myapp Also: DEBUG = True Have tried running with: python manage.py runserver 8001 --insecure and python manage.py runserver 8001 Any help would be much appreciated. Thanks, Jon -
Ckdeditor automatic adding backslah into the end of image url
I have a problem with ckeditor django, it automatically adds \ at the end of images sources. Here is my result from api request <img alt=\"\" src=\"/media/uploads/2019/04/07/pinterest-texttext-quote-hd-wallpaper-inspirational-quote-typography-positive-wallpaperquotes-motivational-feelings.jpg\" /> Could help me to find the problem ? here is my url urlpatterns = [ path('api/', include(router.urls)), path('api-token-auth/', obtain_auth_token, name='api_token_auth'), path('ˆckeditor/', include('ckeditor_uploader.urls')), ] + static(settings.MEDIA_URL, document_root=settings.STATIC_ROOT) and here is the settings.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' CKEDITOR_UPLOAD_PATH = 'uploads' CKEDITOR_RESTRICT_BY_USER = True CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'Advanced', 'width': 758, 'height': 300, }, } -
I am unable to configure views.py
Im using the official django tutorial and copy and pasting from there and when I got to the bit about views and put it in my server started saying SyntaxError: invalid synytax Ive already tried adding url(r'^(?P\d+)/vote/$', views.vote, name='vote'), instead of what i had. File "/Users/Oisin/mysite/polls/urls.py", line 9 url('/', views.detail, name='detail'), ^ SyntaxError: invalid syntax so im meant to just get it to start up but instead im getting syntax error -
Django voting results in double counting
Im trying to simply accomplish that a vote on a post gets count +1 if a user hits the like button on my site but for some reasone it counts not +1, instead it counts +2 if i hit the URL of that post: views.py def post_up_vote (request, pk): post = get_object_or_404(Post, pk=pk) try: if request.method == 'GET': if post.author == request.user: messages.error(request, 'You are trying to vote on a Post you created by your own. Thats not possible.') return redirect('post_detail', pk=post.pk) if Post_Vote.objects.filter(voter=request.user, voted=post).exists(): messages.error(request, 'You already Voted this Post. Double votes are not allowed.') return redirect('post_detail', pk=post.pk) else: post.up_vote = F('up_vote') + 1 post.save() Post_Vote.objects.create(voter=request.user, voted=post) messages.success(request, 'You have successfully Provided an Up-Vote for this Post.') return redirect('post_detail', pk=post.pk) else: messages.error(request, 'Something went wrong, please try again.') return redirect('post_detail', pk=post.pk) except: messages.error(request, 'Something went wrong, please try again.') return redirect('post_detail', pk=post.pk) models.py class Post(models.Model): ... up_vote = models.IntegerField(default=0) down_vote = models.IntegerField(default=0) ... class Post_Vote(models.Model): voter = models.ForeignKey(User, on_delete=models.CASCADE) voted = models.ForeignKey(Post, on_delete=models.CASCADE) published_date = models.DateField(auto_now_add=True, null=True) class Meta: unique_together = ('voter', 'voted') def publish(self): self.published_date = timezone.now() self.save() urls.py url(r'^post/(?P<pk>\d+)/up-vote/$', app.post_up_vote, name='post_up_vote'), if i create a new post on my site and vote on this post with a … -
Unable to render Modelform using CreateView in Django?
I am new to Django and was learning how to render a Modelform in a Django template using CreateView. My form basically is a fileupload and I wanted to use CreateView to render the form but unfortunately nothing happens. What could i be doing wrong ? class BulkSchoolRecord(models.Model): school_record = models.FileField(null=False,blank=False) date_last_modified = models.DateTimeField(auto_now=True) date_added = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): super(BulkSchoolRecord, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('school:bulkschoolrecord', args=[self.id]) class BulkSchoolUploadForm(ModelForm): class Meta: model = BulkSchoolRecord fields = ('school_record',) def __init__(self, *args, **kwargs): # self.user = kwargs.pop('user') super(BulkSchoolUploadForm, self).__init__(*args, **kwargs) class BulkSchoolRecordView(CreateView): template_name = 'school/bulkschool.html' form_class = BulkSchoolUploadForm model = BulkSchoolRecord def get_initial(self, *args, **kwargs): initial = super(BulkSchoolRecordView, self).get_initial(**kwargs) initial['title'] = 'schoolrecord' return initial {% include 'school/base.html' %} {#header#} {% include 'school/header.html' %} {#navigation menu goes here#} {% include 'school/navbar.html' %} {#all sub templates will inherit from the parent file and override their respective block#} {% block bulkschoolrecord %} {% endblock %} {#footer#} {% include 'school/footer.html' %} schoolrecord.html {% extends 'school/index.html' %} {% block bulkschoolrecord %} {% endblock %} -
Separate template for mobile and desktop in django 2.0
I want to have separate templates for desktop and mobile. tried django_mobile but showing error mw_instance = middleware(handler) TypeError: object() takes no parameters my django version is 2.1 post your answer considering i am new to django -
Q: How to limit fields in Form Django 2.2?
I got problem on limiting field shown in forms.ModelForm. I Use Django 2.2 Currently I have models.py class MyModel(models.Model) : user = models.ForeignKey(User, on_delete=models.CASCADE) justchar = models.CharField(max_length=20, blank=True, null=True) admins.py class MyModelAdmin(admin.ModelAdmin) : form=MyModelForm admin.site.register(MyModel,MyModelAdmin) form.py class MyModelForm(forms.ModelForm) : class Meta: fields = ['user'] But the form still shows all fields. I also tried with 'exclude', but got same results Kindly pleas give me any clue. -
Custom field in root of JSON result in Django Rest Framework ListApiView
The result of ListApiView In django rest framework is something like this: { "count": 1023 "next": "https://api.example.org/accounts/?page=5", "previous": "https://api.example.org/accounts/?page=3", "results": [ … ] } I want add a custom field in root of JSON result and not in the results list. { "my_custom_field": ... "count": 1023 "next": "https://api.example.org/accounts/?page=5", "previous": "https://api.example.org/accounts/?page=3", "results": [ … ] } -
Selected dropdown value is NULL when i read it in views.py
I have taken some input from the user and stored it in Django sqllite file and same data im fetching it and displaying in dropdown list but when user selects a value, the selected value is coming as null to the vies.py. I have tried using POST.get also but still, I'm getting NULL from the form. Can any one of you help me knowing my mistake HTML FILE: <form method="post" action="/NewHandBook/ReadCobrand">{% csrf_token %} <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1" style="margin-top: 5px"> <ul class="nav navbar-nav"> <li class="dropdown" style="padding-right: 10px"> <select class="form-control" id="sel1" style="font-family: Courier"> <option name="NewEnvName" value="xyz">xyz</option> </select> </li> </ul> <ul class="nav navbar-nav"> <li class="dropdown" style="font-family: Courier;font-size: 20px;color: ivory"> <input type='radio' name='CobranSelection' value="CobrandName" checked/> <label for="edit-radios-lorem-tortor-erat" class="option" >Cobrand Name | </label> <input type='radio' name='CobranSelection' value="CobrandId"/> <label for="edit-radios-lorem-tortor-erat" class="option" >Cobrand Id </label> </li> </ul> <div class="form-group"> <input type="text" style="margin-top: -1px;font-family: Courier;width: 210px;margin-right: -10px" class="form-control" name="cobrand" placeholder="Eneter Cobrand detail here"> <button type="submit" class="btn btn-default" style="margin-top: -31px;font-family: Courier;margin-left: 230px"> Submit </button> </div> </div><!-- /.navbar-collapse --> </form> urls.py from django.conf.urls import url from . import views urlpatterns = [ url('login', views.login), url('Home', views.fetch_all_env), url('AddEnvironment', views.add_environment), url('GetEnvironment', views.GetEnvironment), url('ReadDb', views.readdb), url('LearnCobrand', views.learncobrand), url('ReadCobrand',views.knowcobrand) ] views.py def … -
How to extend manager method in django?
I would like to extend _filter_or_exclude method on my manager, but for some reason, the method is never called. What I want to achieve is to implicitly filter models, which don't have field deleted = 0 (with both get() and filter()) My models from django.db.models import Model, Manager, Q, QuerySet class BaseManager(Manager): def _filter_or_exclude(self, *args, get_deleted=False, **kwargs): clone = super()._filter_or_exclude(*args, **kwargs) if not get_deleted: clone.query.add(Q(deleted=0)) return clone # Just for sure, I extended the method on a querySet as well class BaseQuerySet(QuerySet): def _filter_or_exclude(self, *args, get_deleted=False, **kwargs): clone = super()._filter_or_exclude(*args, **kwargs) if not get_deleted: clone.query.add(Q(deleted=0)) return clone class BaseModel(Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) deleted = models.IntegerField(default=0) ... objects = BaseManager.from_queryset(BaseQuerySet) class Meta: abstract = True def delete(self, from_db=False, using=None, keep_parents=False): if from_db: super().delete(using, keep_parents) return self.deleted = 1 self.save() class Operation(BaseModel): ... Now when I run Operation.objects.get(id="...") The extended method _filter_or_exclude is not called on the custom manager, but on a default one. What am I doing wrong? -
How to establish connection to APNs
I'm trying to connect to APNs via PyAPNs2 and update Pass in Wallet. Actually I don't understand what's wrong with code. I use this snippet: from apns2.client import APNsClient from apns2.payload import Payload token_hex = 'MY TOKEN' payload = Payload() client = APNsClient('key.pem',password='my_pass', use_sandbox=False, use_alternative_port=False) client.send_notification(token_hex, payload) I use key.pem generated with command in terminal openssl pkcs12 -in "Certificates.p12" -nocerts -out key.pem Also I use token generated by apple for current wallet. But I get this error: ssl.SSLError: [SSL] PEM lib (_ssl.c:3507) I see that problem in key.pem but I don't know how to solve it. -
Relationship between Selenium and tests,py related in Django?
I will start writing my tests.py for a small app I developed. I have not used Selenium before. Therefore, I am not sure if I should learn Selenium first then write my tests.py ? Or write my tests.py first then incorporate Selenium into the tests.py after ? -
Form not saving in UpdateView after overriding post method
I have a template in which I need to perform multiple actions (i.e. updating the form, executing an action). Therefore, two buttons are added in the form: (1) Save changes, (2) Perform action. The template is connected to an UpdateView. Since there are two different actions which need alternative logic, I've overridden the post method in the UpdateView. I've got these two buttons in my template: <div class="m-t-20"> <div class="button-items" style="text-align:right;"> <button type="submit" name="save_plan" class="btn btn-secondary waves-effect waves-light"><i class="fa fa-save"></i>&nbsp;Wijzigingen opslaan</button> <button type="submit" name="execution" class="btn btn-primary waves-effect"><i class="fa fa-check"></i>&nbsp;Onderhoud uitgevoerd</button> </div> </div> The form is as follows: class UpdateMaintenancePlan(forms.ModelForm): class Meta: model = Job fields = ('title_nl', 'description_nl', 'frequency', 'deadline_at', 'company_notes', ) The template is linked to the view below: class MaintenancePlanUpdate(LoginRequiredMixin, UpdateView): login_url = "/login/" redirect_field_name = "redirect_to" model = Job form_class = UpdateMaintenancePlan template_name = "companies/maintenance-update.html" def get_object(self, *args, **kwargs): object = super(MaintenancePlanUpdate, self).get_object() return object def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): form.save() if "save_plan" in request.POST: url = reverse_lazy('dashboard:maintenance-update', kwargs={'pk': self.kwargs['pk']}) messages.add_message(self.request, messages.INFO, 'MESSAGE 1') return HttpResponseRedirect(url) elif "execution" in request.POST: url = reverse_lazy('dashboard:maintenance-update', kwargs={'pk': self.kwargs['pk']}) messages.add_message(self.request, messages.INFO, 'MESSAGE 2') return HttpResponseRedirect(url) Not overriding the post method and the form is saved correctly. … -
Pytest Django Discovers Fixture but Says "Not Found" on the Run
I have a project where each app has a tests module as below: app1/ tests/ __init__.py # whatever test files are app2/ tests/ __init__.py # whatever test files are And also have the project package in the project root as you can guess. It has a testing subpackage, which contains base test cases for models and fields and, of course, fixtures as below: myproject/ __init__.py # settings and related files, you know testing/ __init__.py fixtures.py # for fixtures # other modules for base test classes and stuff So, my overall project structure is: myproject/ # contains standard django stuff and a testing subpackage app1/ # contains app and tests app2/ # so as above # so on and so forth And the pytest.ini content in project root is as below: [pytest] DJANGO_SETTINGS_MODULE = myproject.settings.development python_files = test_*.py myproject/testing/fixtures.py addopts = -s console_output_style = count log_cli_level = DEBUG log_print = True So, assuming myproject/testing/fixtures.py contains a fixture as below: # assuming i've imported related stuff @pytest.fixture # might have different scope def foo(): """does foo""" return "foo" And later on, I do pytest --fixtures to see if pytest properly discovers my fixture and so it does, which means there should not … -
Unable to send messages to kafka from django application using kafka-python
I have a Django based web application in which I am trying to integrate Kafka with the help of this library named kafka-python. However when I am trying to send a message to a particular topic I am getting a time out error stating : Traceback (most recent call last): File "/home/paras/vertex/vertex-1.6/vertex-portal-backend/vertex_app/kafka_service.py", line 67, in send_message x = producer.send(topic, json_data) File "/home/paras/.local/lib/python3.6/site-packages/kafka/producer/kafka.py", line 555, in send self._wait_on_metadata(topic, self.config['max_block_ms'] / 1000.0) File "/home/paras/.local/lib/python3.6/site-packages/kafka/producer/kafka.py", line 682, in _wait_on_metadata "Failed to update metadata after %.1f secs." % (max_wait,)) kafka.errors.KafkaTimeoutError: KafkaTimeoutError: Failed to update metadata after 60.0 secs. Producing message : def put_order_into_kafka(order,obj) : try : if order is None or offering is None : raise Exception("Unable to put order into queue order or offering is null") topic_name = create_kafka_topic_name(obj) send_message(topic_name,order) except Exception as e : print(e) Kafka Service #kafka_service.py from kafka import KafkaProducer from kafka.admin import KafkaAdminClient, NewTopic from .constants import KAFKA_BROKER_URL import json KAFKA_PRODUCER = None def get_kafka_producer(): KAFKA_PRODUCER = init_kafka_producer_instance() return KAFKA_PRODUCER def init_kafka_producer_instance(): try: if KAFKA_PRODUCER is not None : return KAFKA_PRODUCER producer = None producer = KafkaProducer(bootstrap_servers=[ KAFKA_BROKER_URL], value_serializer=lambda x: json.dumps(x).encode('utf-8')) return producer except Exception as e: import traceback print(traceback.format_exc()) return None def create_kafka_topic_instance(topic_name,num_partitions=1,replication_factor=1) : try : if topic_name … -
Django, why would page render objects that have been deleted from database
I am storing and object id in session and later getting it to query and display objects of that models, but when i delete this id from session and also delete this objects from the DB, i still get this objects after reloading the page which is not what i want, see code this is where i am deleting the objects from the db and deleting the session def reset(request): try: id = request.session.get('id') if id: Item.objects.filter(order=id).all().delete() Order.objects.get(pk=id).delete() del request.session['id'] print('Id have been deleted ', request.session['id']) return JsonResponse('The current order has been delete', safe=False) else: print('There\'s no order') return JsonResponse('There was no order', safe=False) except Exception as e: return JsonResponse('An error occured here ' + str(e), safe=False) This is where i am querying and rendering objects to template after testing if id is in session before querying @login_required def dashboard(request): customer_form = CustomerInfoForm() form = TransactionForm(initial={'tax':0,'price':0, 'price_per_item':0}) try: if 'id' in request.session: id = request.session['id'] print('Id in dashboard is ', id) order = Order.objects.get(pk=id) sum_of_price = order.item_set.all().aggregate(Sum('price')) #Get sum of all item prices. if sum_of_price : context['price'] = sum_of_price['price__sum'] context['current_order'] = order.item_set.all() form = TransactionForm(initial={'tax':0,'price':0, 'price_per_item':0,'contact':order.customer_contact}) context['form'] = form context['customer_form'] = customer_form return render(request, 'main/dashboard.html', context) except Exception as e: … -
how to get the log of all the external http call from python
In my django project, I can list all the calls requested from the browser can by inspecting browser. But there are a number of http calls from python to other servers for getting resources. Some of these calls are called from views, some from other functions and some from template tags. How can I list all the external http requests from my python end to other servers? -
How To Fetch Related Category Products in Python Django From Database Table?
Hey Python Django Developers, I have App inside my django project, and app is called coupons also i got app called store both these app related each other mean There are many coupons related store for Example: Coupon1, Coupon2 and Coupon3 belongs to Store1, I hope you go the structure, If you have any question ask. Now What i want is: I want when user click on any of these coupons Coupon1, Coupon2 Or Coupon3 user should see list of all coupons in seperate view which related to Store1. Please guide me how i can do it ?, If you want to see my code i can show ask me which code you want to see? Thanks Moiz -
Connect django model to different table name with same structure
I have a database where I import data from the stock market. This will all be identical tables with only the date differing. How would I connect a django model with a dynamic table name? -
Where is the proper place to implement "LOGOUT" function in PasswordChangeView?
Hello Stackoverflow community. Where is the best place to implement LOGOUT function in PasswordChangeView I tried class PasswordCorrectionView(SuccessMessageMixin, LoginRequiredMixin, PasswordChangeView): template_name = "admin/password_change.html” form_class = PwdChgForm def post(self, request, *args, **kwargs): logout(request) # here return PasswordChangeView.post(self, request, *args, **kwargs) but it rises: NotImplementedError at /account/password/change Django doesn't provide a DB representation for AnonymousUser. That's reasonable cos I cant save AnonymousUser password anyway. So question is what method is the best one to override here in PasswordChangeView??? Or second option override some method in the forms: class PwdChgForm(PasswordChangeForm): def save(self, commit=True): self.user.is_activated = False user_registrated.send(PwdChgForm, instance=self.user) # signal to the email sender PasswordChangeForm.save(self, commit=True) I need user to logout after he has chaged his password (then confirm it via email, etc) All this work except LOGOUT -
Django 2.1 Token matching query does not exist
I've been trying to implement user authenitication in Django using rest_framework.authtoken as in this guide. My test cases, which test for a range of different errors that could arise while a user logs in, are working properly before access tokens are introduced into the code. For some reason, when I add in a check for the token returned in an Http response, I get the error: rest_framework.authtoken.models.Token.DoesNotExist: Token matching query does not exist. I've added in all of the relevant imports that should be needed to check for tokens so could there be a function that was relocated to a different library in one of the more recent django versions? What might be causing the issue? test.py from django.urls import reverse from rest_framework.test import APITestCase from django.contrib.auth.models import User from rest_framework import status from rest_framework.authtoken.models import Token class AccountsTest(APITestCase): def setUp(self): # We want to go ahead and originally create a user. self.test_user = User.objects.create_user('testuser', 'test@example.com', 'testpassword') print('test user:' + str(self.test_user)) # URL for creating an account. self.create_url = reverse('account-create') def test_create_user(self): """ Ensure we can create a new user and a valid token is created with it. """ data = { 'username': 'foobar', 'email': 'foobar@example.com', 'password': 'somepassword' } response … -
django sitemap has no style information
I have setup a django sitemap using the sitemap framework built into django. However although the content of the sitemap looks fine it doesn't generate the typical style / format information normally for a sitemap. And when reviewing in the browser I see the error: This XML file does not appear to have any style information associated with it. The document tree is shown below. Apart from this error the sitemap displays correctly: <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> <loc>http://www.myexample.com/</loc> <changefreq>daily</changefreq> <priority>1.0</priority> </url> <url> <loc>http://www.myexample.com/about/</loc> <changefreq>daily</changefreq> <priority>0.9</priority> </url> <url> .... my sitemap file sitemaps.py is: from django.contrib.sitemaps import Sitemap from django.urls import reverse class HomeSitemap(Sitemap): """Reverse static views for XML sitemap""" changefreq = "daily" priority = 1.0 def items(self): return ['home', ] def location(self, item): return reverse(item) class StaticSitemap(Sitemap): """Reverse static views for XML sitemap""" changefreq = "daily" priority = 0.9 def items(self): return ['about', 'faq', 'contact', 'terms', 'privacy', 'signup'] def location(self, item): return reverse(item) urls.py relevant section ... sitemaps = {'home': HomeSitemap, 'static': StaticSitemap} ... url(r'^sitemap\.xml/$', sitemap, {'sitemaps': sitemaps}, name='signup'),