Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Saving a Serializer in Django
When I'm trying to save a model object (its name here is 'RSS) in the view's post() it doesn't get saved, how can I save the model instance 'rss' from the view's post()? In the Serializers class: class RSSSerializer(serializers.ModelSerializer): class Meta: model = RSS fields = ('feed_url', 'website_url', 'description', 'title') def create(self, validated_data): rss = RSS(**validated_data) rss.created_at = datetime.now() rss.last_scan_time = '2001-01-01 00:00:00' rss.id = None return rss In the View class: class RSSList(APIView): def post(self, request): serializer = RSSSerializer(data=request.data) if serializer.is_valid(): print("saving rss post") serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Page Not Found django
Why is this happening? I do everything according to the instructions. I study. urls.py from django.conf.urls import url,include from django.contrib import admin from . import views urlpatterns = [ #url(r'^$',views.main,name="main"), url(r'^post/(?P<id>[0-9]+)/', views.post_detail, name='post_detail'), ] views.py from django.shortcuts import render from django.utils import timezone from .models import Post from django.shortcuts import render, get_object_or_404 # Create your views here. def post_detail(request,id): post = get_object_or_404(Post, pk=id) return render(request, 'main/post_detail.html', {'post': post}) post_detail.html {% extends 'main/base.html' %} {% block content %} <div class="post"> {% if post.published_date %} <div class="date"> {{ post.published_date }} </div> {% endif %} <h1>{{ post.title }}</h1> <p>{{ post.text|linebreaksbr }}</p> </div> {% endblock %} What to do? Even instead of id put pk, but nothing helps. -
How to show database element after push of a button
I have stored the answers to a test in a database, and I would like the answer of a specific question to appear on the same page, via an alert, after the user pressed the button. What should I do? {% extends 'polls/base.html' %} {% block title %}{% endblock %} {% block content %} {% if prova.questao_set.all %} <h2>Questões do {{prova.tipoProva}} {{prova.anoProva}}</h2> <ul id="questoes"> {% for questao in prova.questao_set.all %} <hr id="linha" /> {% if questao.statusQuestao == '1' %} <h3>Questão {{questao.idQuestao}}</h3> {% if questao.textoQuestao is not None %} <p>{{questao.textoQuestao}}</p> {% endif %} {% if questao.imagemQuestao %} <div class="col-xs-15" align="center"> <img class="img-responsive" id="img1" src="/{{questao.imagemQuestao}}"> <br> </div> {% endif %} {% if questao.imagem2Questao %} <div class="col-xs-15" align="center"> <img class="img-responsive" id="img2" src="/{{questao.imagem2Questao}}"> <br> </div> {% endif %} {% if questao.perguntaQuestao is not None %} <p>{{questao.perguntaQuestao}}</p> {% endif %} {% if prova.questao_set.all %} <ul> {% for opcao in questao.opcao_set.all %} {% if questao.tipoQuestao == '2' %} <form action="" id="opcoes"> <script> function getInputValue(name){ var resposta = document.getElementsByName("respostas"); for(var i = 0; i < resposta.length; i++){ if(resposta[i].checked){ return resposta[i].value; } } return null; } </script> <input type="radio" name="opcao_escolhida" value="A"><label for='{{opcao.aOpcao}}'>a) {{opcao.aOpcao}}</label><br> <input type="radio" name="opcao_escolhida" value="B"><label for='{{opcao.bOpcao}}'>b) {{opcao.bOpcao}}</label><br> <input type="radio" name="opcao_escolhida" value="C"><label for='{{opcao.cOpcao}}'>c) {{opcao.cOpcao}}</label><br> <input type="radio" name="opcao_escolhida" … -
Apache/2.4.18 (Ubuntu) mod_wsgi/4.3.0 Python/3.5.2 configured -- resuming normal operations
Django 1.11.7 I installed the python3.6 in the virtual environment. why is it Python/3.5.2 here? and I cannot visit the web 127.0.0.1 (500 internal server error) [wsgi:error] [pid 61905:tid 140688926893824] [remote 127.0.0.1:33456] mod_wsgi (pid=61905): Target WSGI script '/home/ubuntu/.../wsgi.py' cannot be loaded as Python module. [wsgi:error] [pid 61905:tid 140688926893824] [remote 127.0.0.1:33456] mod_wsgi (pid=61905): Exception occurred processing WSGI script '/home/ubuntu/.../wsgi.py'. [wsgi:error] [pid 61905:tid 140688926893824] [remote 127.0.0.1:33456] Traceback (most recent call last): [wsgi:error] [pid 61905:tid 140688926893824] [remote 127.0.0.1:33456] File "/home/ubuntu/.../wsgi.py", line 32, in [wsgi:error] [pid 61905:tid 140688926893824] [remote 127.0.0.1:33456] from django.core.wsgi import get_wsgi_application [wsgi:error] [pid 61905:tid 140688926893824] [remote 127.0.0.1:33456] ImportError: No module named 'django' how to solve above problem? Help! thks!!! -
Error while running migrate for django-hordak
I want to use django-hordak in my application for accounting purpose and have followed the official tutorial at http://django-hordak.readthedocs.io/en/latest/. I add the applications "mptt" and "hordak" in INSTALLED_APPS and when I run ./manage.py migrate, it throws following error on the console: Please help! Thanks -
Django - unable to get a foreign key attribute displayed
I am writing a Django webapp. I need some help on why my sidebar is not showing "company.name" which is a foreign key attribute. https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/templates/employee/base.html <h4>{{ request.user.get_full_name }}</h4> <--- can display <h5>{{ request.employee.company.name }}</h5> <--- cannot display https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/models.py class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) company = models.ForeignKey(Company) <--- this is the foreign key Here you can see the problem, its not showing the "company name" below https://imgur.com/a/noMoA -
Nginx blocks Apache2 on different port
I have my virtual host on CentOS 6 I've installed Apache2 going through this tutorial And then I've prepared /conf.d/vhost.conf file : <VirtualHost *:8000> ServerAdmin myEmail.gmail.com ServerName testApp ServerAlias 127.0.0.1 DocumentRoot /home/myUser/testApp WSGIScriptAlias /home/myUser/testApp/testApp/wsgi.py ErrorLog /home/myUser/testApp/testApp/error.log CustomLog /home/myUser/testApp/testApp/access.log combined </VirtualHost> and don't know why, but if I try to execute sudo service httpd start Then I see a message: Address already in use: make_sock: could not bind to address 0.0.0.0:443 The 443 port is using by nginx, in Apache2 httpd.conf i selected Listen 8000 So everything should be okay. Does anyone know, what I am doing wrong ? Thanks in advance, -
Django app on apache server with VPS
I've installed mod_wsgi on my apache server. And when I configure WSGIScriptAlias to hello.wsgi to test, it works. But to my Django wsgi.py, it gives 500. In error log it says 'End of script outpt before headers: wsgi.py' What am i missing? -
How to get name of tag from id in Django
I take list of medicines in "rlist" rlist = [] #dName = disease name and r = resulted disease rlist.append(Disease.objects.filter(dName = r).values_list('medicine',flat=True)) By running this statements, I have ids of taggable manage "medicine" Medicine = [<QuerySet [7]>, <QuerySet [27, 28, 29, 30]>] But, I want name of medicine instead of id. How can I get that??? -
Deploying django to production server with nginx/gunicorn in vps server
I am trying to serve my django project live. Using nginx/gunicorn/mysql/supervisor/virtualenv. I am following this tutorial. https://simpleisbetterthancomplex.com/series/2017/10/16/a-complete-beginners-guide-to-django-part-7.html#configuring-gunicorn But stuck with one (don't know simple of big) problem. I am using linux vps. i have vesta cp installed in my system. To manage my server. So i don't know it has any side effect on my process or what. I tried everything working just perfect . I tired gunicorn DjangoBeginnersGuide.wsgi:application --bind 0.0.0.0:8001 python manage.py runserver sudo supervisorctl status boards sudo service nginx restart. Each command work just fine but still i can't see my site in my requested domain(live not localhost) . Also there has no chance for the domain to not work. As i am running other subdomains in this server as well. Also my this domain is showing the default page of my server. -
Gunicorn sock file not generated
I have an django application which I want to run using gunicorn and nginx. I have my application installed in this directory: /website/davidbien/ I get to the point where I run django's dev webserver and can access that. I then run: gunicorn davidbien.wsgi:application --bind 0.0.0.0:8000 And this works fine as well. After this I create a script: #!/bin/bash NAME="davidbien" DJANGODIR=/website/davidbien SOCKFILE=/website/virtual/run/gunicorn.sock USER=ec2-user GROUP=ec2-user NUM_WORKERS=3 DJANGO_SETTINGS_MODULE=davidbien.settings DJANGO_WSGI_MODULE=davidbien.wsgi echo "Starting $NAME as `whoami`" cd $DJANGODIR source ../virtual/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR exec gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --user=$USER --group=$GROUP \ --bind=unix:$SOCKFILE \ --log-level=debug \ --log-file= And this runs fine as well as I get: Starting gunicorn 19.7.1 Arbiter booted Listening at: unix:/website/virtual/run/gunicorn.sock (3354) [INFO] Using worker: sync [INFO] Booting worker with pid: 3361 [INFO] Booting worker with pid: 3362 [INFO] Booting worker with pid: 3363 [DEBUG] 3 workers The problem is that .sock file is not generated at all! I can't move on with nginx config as this file is not available. I gave 777 access to /website/ folder and everything inside it but this still doesn't work. I tried sudo as well and nothing. Logs show that it's … -
View is callable still getting error View must be Callable-Django
Hi I am writing my first Django program. I am getting this error: url(r'^hello/',view.Users().getUsers(), name='hello') File"C:\Users\jayant.brahmchari\AppData\Local\Programs\Python\Python36\lib\si te-packages\django\conf\urls\__init__.py", line 85, in url raise TypeError('view must be a callable or a list/tuple in the case of include().') TypeError: view must be a callable or a list/tuple in the case of include(). this is my urls.py: from django.conf.urls import url from django.contrib import admin from . import view urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^hello/',view.Users().getUsers(), name='hello') ] this is view.py: from django.http import HttpResponse class Users: def getUsers(self): return HttpResponse("Hello Users") According to people in forums url do not accept string as second argument but in my code view is already callable but still getting this error. Thanks in advance. -
How to make a search engine for my comments
I am triying to make a search engine through the posted comments. The goal is to search the comments as easiest as possible. See below the architecture of the program: views.py class ComentarioListar (LoginRequiredMixin,ListView): login_url='/' redirect_field_name='redirigido' model = Comentario template_name = 'home/comentario_listar.html' def busqueda (self): q=request.GET.get('q','') querys = (Q(titulo__icontains=q)) comentario=Comentario.objects.filter(querys) return render(request, 'search.html', {'comentarios':comentarios}) urls.py urlpatterns = [ url(r'^listar$', ComentarioListar.as_view(), name="listar"), url(r'^search$',busqueda, name="search"),] models.py class Comentario (models.Model): titulo = models.CharField(max_length=50) texto = models.CharField(max_length=200) autor = models.ForeignKey (Perfil, null=True, blank=True, on_delete=models.CASCADE) fecha_publicacion = models.DateTimeField(auto_now_add=True) tag = models.ManyToManyField(Tags, blank=True) def __str__(self): return (self.titulo) cometario_listar.html (where I have created the search button) <form id="searchform" action="search/" method="GET" accept-charset="utf-8"> <button class="searchbutton" type="submit"> <i class="fa fa-search"></i> </button> <input class="searchfield" id="searchbox" name="q" type="text" placeholder="Search" id="busqueda"> </form> {% endblock %} search.html {% extends 'base/base.html' %} {% block content %} <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="en"> <head> <title>Search{% if query %} Results{% endif %}</title> </head> {% if query %} <h2>Results for "{{ query|escape }}":</h2> {% if results %} <ul> {% for Comentario in results %} <li>{{ Comentario|escape }}</l1> {% endfor %} </ul> {% else %} <p>No hay resultados</p> {% endif %} {% endif %} </body> </html> {% endblock %} The problem is that it does not work. … -
How to translated regex in url (Django)
I have the following url: url(_(r'^personality/(?P<name>[\w-]+)/$'), personality, name='personality'), and my .po file contains the following: #: website/urls.py:31 msgid "^ personality/(?P< name >[\\w-]+)/$" msgstr "^personalita/(?P<name>[\\w-]+)/$" a typical url would be: /personality/egocentric/ I want to translate it to: /personalita/egocentrico/ My problem is: if I'm on the page of /personality/egocentric/ and switch languages, the url becomes /personalita/egocentric How can I translate the regex part and substitute the url? -
Django channels - websocket force closed due to back pressure
I'm using django channels for a website, and some how suddenly the open websockets are closed, and can't be open again without restarting the django server. Following exception appear in the console: "WebSocket force closed for %s due to connect backpressure" Searching the cause, I found in daphne code the message: # Send over the connect message try: self.channel_layer.send("websocket.connect", self.request_info) except self.channel_layer.ChannelFull: # You have to consume websocket.connect according to the spec, # so drop the connection. self.muted = True logger.warn("WebSocket force closed for %s due to connect backpressure", self.reply_channel) # Send code 503 "Service Unavailable" with close. raise ConnectionDeny(code=503, reason="Connection queue at capacity") else: self.factory.log_action("websocket", "connecting", { "path": self.request.path, "client": "%s:%s" % tuple(self.client_addr) if self.client_addr else None, }) Does anyone know which spec should be followed to avoid the error? -
url not found - Django
I'm getting "URL not found error" on my website. These are my files: myapp.urls: url(r'^produkty/', include('supplement.urls', namespace='supplements')), supplement.urls: urlpatterns = [ url(r'^(?P<slug>[-\w]+)/$', SupplementDetailView.as_view(), name='detail'), url(r'^$', SupplementListView.as_view(), name='list'),] supplement.views: class SupplementListView(ListView): def get_queryset(self): return Supplement.objects.all() class SupplementDetailView(DetailView): queryset = Supplement.objects.all() NOTE: Both queryset = Supplement.objects.all() and get_queryset(self): return Supplement.objects.all() don't work in SupplementDetailView supplement.models: class Supplement(models.Model): name = models.CharField(blank=False, null=False, help_text=_("product's name"), max_length=50) price = models.IntegerField(blank=True, null=True) portion = models.CharField(max_length=100, blank=True, null=True, help_text=_("portion")) img = models.ImageField(default='kitchen/No-image-available.jpg', upload_to='products/', blank=True, null=True) description = RichTextField() contains = models.CharField(blank=True, null=True, max_length=3000, help_text=_("contains")) slug = models.SlugField(max_length=150, blank=True, null=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('supplements:detail', kwargs={"slug": self.slug}) class Meta: ordering = ['-name'] verbose_name = _('supplement') verbose_name_plural = _('supplements') def rl_pre_save_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = unique_slug_generator(instance) pre_save.connect(rl_pre_save_receiver, sender=Supplement) Templates for SupplementListView and SupplementDetailView are placed in BASE_DIR/supplement/templates/supplement. NOTE: SupplementDetailView works like a charm. It loads the information about product passed in a in url (for example: myapp.pl/produkty/product-slug), but the list of products (myapp.pl/produkty) returns "URL not found error" Thank You for your help in advance, I've been struggling with that error for quite a while now. -
The callback function object in Django URLconf is not called
I am learing Django on Django at a glance | Django documentation | Django When introducing URLconf It reads: To design URLs for an app, you create a Python module called a URLconf. A table of contents for your app, it contains a simple mapping between URL patterns and Python callback functions. Nevertheless, a callback function is not called. mysite/news/urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^articles/([0-9]{4})/$', views.year_archive), ] print('callback funtion:',views.year_archive) output: callback function: <function views.year_archive at 0x1039611e0> So it a funtion object which is not called. I suppose it should be views.year_archive() to enable it to call. If not called,how does it work? I assume there a decorator to process it in parent class. I check the source codes of urldjango.conf.urls | Django documentation | Django The key statement is: elif callable(view): return RegexURLPattern(regex, view, kwargs, name) I dig on to explore LocaleRegexProvider, RegexURLPattern django.urls.resolvers | Django documentation | Django. No appopriate codes were found to call the callback function views.year_archive What's the mechanism of its working? -
Django Rest Framework SearchFilter gives HTTP 301 Moved Permanently
Please consider my issue. I'm trying to implement Django Rest framework filtering, specifically, SearchFilter, but getting HTTP 301 Moved Permanently response. I'm strictly following documentation, but unfortunately, didn't get desired result. The code is following: views.py class PartnerAPI(generics.ListAPIView): queryset = Questionnaire.objects.all() serializer_class = QuestionnaireSerializer search_fields = ('name', 'phone', 'passport') def list(self, request): queryset = self.get_queryset() serializer = QuestionnaireSerializer(queryset, many=True) return Response(serializer.data) settings.py ... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'django_filters', 'loans', ] ... REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ( 'django_filters.rest_framework.DjangoFilterBackend', 'rest_framework.filters.SearchFilter', ) } models.py class Questionnaire(models.Model): created = models.DateTimeField( auto_now_add=True) modified = models.DateTimeField( auto_now=True) name = models.CharField( max_length=255) birthday = models.DateField( blank=True, null=True) phone = models.CharField( max_length=10, blank=True, null=True) passport = models.CharField( max_length=255, blank=True, null=True) score = models.PositiveSmallIntegerField( blank=True, null=True) urls.py ... urlpatterns = ( url(r'^questionnaires/$', views.PartnerAPI.as_view()), ... ) The request i'm making is http GET http://127.0.0.1:8000/questionnaires?search=123 where 123 is the value of phone field. Also, i've tried http GET http://127.0.0.1:8000/questionnaires?search=123/, but got HTTP 301 Moved Permanently response in both cases. Please, please help me. -
raise TypeError: view must be a callable or a list/tuple in the case of include()
I'm new in django, i try some code in internet but I got some problem. here is my error : error warning here is my code of urls.py urls.py here is my views.py views.py -
Python / Django handling errors UNIQUE constraints
Good Day. I'm writing a little script that pulls RSS data using Feedparser. I got it working up to where it pulls everything I need to my database and store it there. Now to avoid data from being duplicated, I set Unique = True in my models. Of course, now I'm dealing with the error return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: UNIQUE constraint failed: jobrss_rssjob.link Okay, sort of good it's not duplicating data. However, it completely crashes the script so it will just stop. Obviously I now need to write an exception for errors - and that's pretty much where I'm stuck cause they are also throwing errors at me. Here's my code: from __future__ import unicode_literals import feedparser from django.utils import timezone import json from django.db import IntegrityError from jobrss.models import RSSJob try: def run(): sources = [ "https://mybroadband.co.za/vb/external.php?type=RSS2&forumids=269", "http://www.bizcommunity.com/rssjobs.aspx?l=196&c=11&s=Developer&sm=1" ] data = [] for url in sources: data.append(feedparser.parse(url)) for data in data: for post in data.entries: title = post.title link = post.link add = RSSJob() add.title = title add.link = link add.save() print("Added successfully") except IntegrityError: print("Data Already exists") Any recommendation how I can improve this? Kind Regards. :) -
django: Fatal Python error: Cannot recover from stack overflow. Process finished with exit code 134 SIGABRT
On starting my django project, I am encountering this error: Fatal Python error: Cannot recover from stack overflow. Full trace as follows: Thread 0x00007f9dcdaba700 (most recent call first): File "/usr/lib/python3.5/socket.py", line 576 in readinto File "/home/grzsqrrl/my_proj/lib/python3.5/site-packages/django/core/servers/basehttp.py", line 140 in handle File "/usr/lib/python3.5/socketserver.py", line 681 in __init__ File "/usr/lib/python3.5/socketserver.py", line 354 in finish_request File "/usr/lib/python3.5/socketserver.py", line 625 in process_request_thread File "/usr/lib/python3.5/threading.py", line 862 in run File "/usr/lib/python3.5/threading.py", line 914 in _bootstrap_inner File "/usr/lib/python3.5/threading.py", line 882 in _bootstrap Thread 0x00007f9dce2bb700 (most recent call first): File "/usr/lib/python3.5/socket.py", line 576 in readinto File "/home/grzsqrrl/my_proj/lib/python3.5/site-packages/django/core/servers/basehttp.py", line 140 in handle File "/usr/lib/python3.5/socketserver.py", line 681 in __init__ File "/usr/lib/python3.5/socketserver.py", line 354 in finish_request File "/usr/lib/python3.5/socketserver.py", line 625 in process_request_thread File "/usr/lib/python3.5/threading.py", line 862 in run File "/usr/lib/python3.5/threading.py", line 914 in _bootstrap_inner File "/usr/lib/python3.5/threading.py", line 882 in _bootstrap Thread 0x00007f9dceabc700 (most recent call first): File "/usr/lib/python3.5/socket.py", line 576 in readinto File "/home/grzsqrrl/my_proj/lib/python3.5/site-packages/django/core/servers/basehttp.py", line 140 in handle File "/usr/lib/python3.5/socketserver.py", line 681 in __init__ File "/usr/lib/python3.5/socketserver.py", line 354 in finish_request File "/usr/lib/python3.5/socketserver.py", line 625 in process_request_thread File "/usr/lib/python3.5/threading.py", line 862 in run File "/usr/lib/python3.5/threading.py", line 914 in _bootstrap_inner File "/usr/lib/python3.5/threading.py", line 882 in _bootstrap Current thread 0x00007f9dcf2bd700 (most recent call first): File "/usr/lib/python3.5/inspect.py", line 2403 in __init__ File "/usr/lib/python3.5/inspect.py", line … -
django periodically sync SQLite and sql server
How can I periodically sync data from an sql server database to SQLite(or even mysql) used in django. I'm trying to develop an HR Management System using Django. I need to sync attendance data of employees from the Biometric Fingerprint Attendance System which are stored in a sql server database. -
Django not rendering information to the databse
so I have been trying to save the information from the frontend to the backend in Django. However when I check my database on Django it is not there. Can you please check what I am doing wrong, im fairly new at Django? Thank you! view.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.contrib.auth import login, authenticate from django.contrib.auth.forms import UserCreationForm from django.shortcuts import render, redirect #from django.contrib.auth import views as auth_views #from . import views # Create your views here. def login(request): return render(request, 'login.html') def signup(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() #username = form.cleaned_data.get('username') #raw_password = form.cleaned_data.get('password1') #user = authenticate(username=username, password=raw_password) #login(request, user) return redirect('login.html') else: form = UserCreationForm() return render(request, 'templates/signup_form.html', {'form': form}) return render(request, 'signup_form.html') signup_form.html {% extends 'signup.html' %} {% block body %} <form method = "post"> {% csrf_token %} {{ form.as_p}} </form> {% endblock %} models.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models # Create your models here. -
Django - Forms - What does (?P\d+)/$ signify? Help please
I am new to django. I was creating forms in django with the help of an online tutorial. I didnot understand a line in the urls.py file. Can someone explain what exactly it means? from django.conf.urls import url from . import views from . views import BlogListView, BlogDetailView, BlogCreateView urlpatterns = [ url(r'^$', views.BlogListView.as_view(), name='post_list'), url(r'^post/(?P<pk>\d+)/$', BlogDetailView.as_view(), name='post-detail'), url(r'^post/new/$', BlogCreateView.as_view(), name='post_new'), url(r'^post/(?P<pk>\d+)/edit/$', BlogUpdateView.as_view(), name='post_edit'), ] I did not understand the following line: url(r'^post/(?P<pk>\d+)/$' What does (?P\d+)/$ signify? Help please -
Conditionally pass model decleration in Meta to django ModelForm
Is there a way to conditionally pass the model class to the meta in a model form before instantiation / the metaclass magic happens? I have a lot of "specification" fields that need to have update / create views and they all have the same fields excluded. Hence, I can just set excludes and the model form will do the rest for all of them. Thus, I only really need one form / one update form for all of this. It'd be exceedingly redundant to define update and create views for all of these... With this I can just use one update and one create view for all of them passing the form_class in my urls.py as BaseUpdate(form_class=MyBaseForm(ModelClass)) and BaseCreate(form_class=MyBaseForm(ModelClass))