Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using django_xhtml2pdf with django 1.11" error: context must be a dict rather than Context."
I did see the other answers on this, and it confused me because I am just using what was documented here: https://spapas.github.io/2015/11/27/pdf-in-django/#django-integration for getting the django_xhtml2pdf stuff to work. My view is as such: def providers_plain_old_view(request): resp = HttpResponse(content_type='application/pdf') context = { 'providers': Provider.objects.all() } result = generate_pdf('ipaswdb/provider/providers_plain_old_view.html', file_object=resp, context=context) return result Which I know now is bad in django 1.11.14 I am using, but no idea how to fix the error: Traceback (most recent call last): File "D:\Python27\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "D:\Python27\lib\site-packages\django\core\handlers\base.py", line 249, in _legacy_get_response response = self._get_response(request) File "D:\Python27\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "D:\Python27\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Programming\web\ipa_django\mysite\ipaswdb\views.py", line 312, in providers_plain_old_view result = generate_pdf('ipaswdb/provider/providers_plain_old_view.html', file_object=resp, context=context) File "D:\Python27\lib\site-packages\django_xhtml2pdf\utils.py", line 62, in generate_pdf generate_pdf_template_object(tmpl, file_object, context) File "D:\Python27\lib\site-packages\django_xhtml2pdf\utils.py", line 39, in generate_pdf_template_object html = template_object.render(Context(context)) File "D:\Python27\lib\site-packages\django\template\backends\django.py", line 64, in render context = make_context(context, request, autoescape=self.backend.engine.autoescape) File "D:\Python27\lib\site-packages\django\template\context.py", line 287, in make_context raise TypeError('context must be a dict rather than %s.' % context.__class__.__name__) TypeError: context must be a dict rather than Context. "GET /ipaswdb/provider_roster/ HTTP/1.1" 500 86485 I mean it wants me to call the generate_pdf function a different way … -
How do Query File Field That is related foreign key
Hello guys am stuck trying all i can to query file in a foreignkey but it doesn't work django throws up an error i have been trying to do this for long now I just gave and now i am back to it need help! from __future__ import unicode_literals from django.db import models class Examination(models.Model): examination_name = models.CharField(max_length=50, unique=True) class Meta: verbose_name='examination' verbose_name_plural='examinations' def __unicode__(self): return self.examination_name class YearAndExaminationName(models.Model): exam_name = models.ForeignKey(Examination) examination_year = models.CharField(max_length=4) class Meta: verbose_name='year and examination name' verbose_name_plural='year and examination names' def __unicode__(self): return self.examination_year class PastQuestion(models.Model): year_and_exam_name = models.ForeignKey(YearAndExaminationName) file_name = models.CharField(max_length=40, default='self') file = models.FileField(upload_to='uploads/', max_length=100,) posted_by = models.CharField(max_length=40) def __unicode__(self): return self.file_name What i intended doing is to get pdf to display files by referencing from view via id or pk but when i search stackoverflow or google what I get is how to convert html to pdf. -
Django tests with ElasticSearch
I know this question has been asked many times, many suggesting to separate integration tests from unit tests. But is there a plugin/package to create new ES indexes that mimics how Django creates a new empty database for running tests? In theory it doesn't sound that difficult right? A package that creates new indexes eg. test_index_201709011234 to correspond to transactional test cases, and delete those indexes after test run. -
Celery + Docker + Django can't run async job
I am new with celery and docker and I have problem with that. I have django project with following structure: generic generic celery.py ... web tasks.py generic/celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery import logging logger = logging.getLogger("Celery") os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'generic.settings') app = Celery('generic') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() web/tasks.py from future import absolute_import, unicode_literals from django.conf import settings from generic.celery import app @app.task def foo(): ... docker-compose.yml version: '3.0' services: db: image: postgres web: build: . command: python3 manage.py runserver 0.0.0.0:8000 volumes: - .:/src ports: - "8000:8000" depends_on: - db redis: image: redis:latest container_name: rd01 ports: - '6379:6379' celery: build: . container_name: cl01 command: celery worker --app=app.tasks volumes: - ..:/src links: - db - redis When I run my app ModuleNotFound is raised ModuleNotFoundError: No module named 'app.tasks' I have also tried to write in docker-compose.yml: command: celery worker --app=generic.tasks and I recieved AttributeError: module 'generic.tasks' has no attribute 'celery' and I also have tried: command: celery worker --app=generic.tasks and: ModuleNotFoundError: No module named 'web' I have also tried pass a module as include parameter to Celery object Can anyone tell me what is wrong with that? I have found many similar posts but no answer didn't … -
Django Admin and Rest Framework Forms not showing up
My forms for creating a new objects in the database are not showing up in my admin or my rest framework pages. I am using the latest versions of both python and django If anyone knows what causes this any help would be greatly appreciated. -
Getting the amount of guests in bookings made django
If each a user goes into an event they can make an booking, but each event only has a certain amount of space open. I would like to show in the event that there are 5 out of 10 seats left. I just can't seem to find the sum of guests that have already booked with a status of being active or pending. here is my events model class Events(models.Model): ACTIVE = (('d', "Deactivated"), ('e', "Expired"), ('a', "Active"), ('b', "Drafts"),) ALCOHOL = (('0','No bring own alcohol'),('1','There will be complimentary wine pairing')) user = models.ForeignKey(User, on_delete=models.CASCADE) active = models.CharField(max_length=1, default='b', choices=ACTIVE) title = models.CharField(max_length=50, blank=True, default='') description = models.TextField(max_length=500, blank=True, default='') date = models.DateField() time = models.TimeField() price = models.CharField(max_length=240, blank=True, default='') seats = models.IntegerField() alcohol_choice = models.CharField(max_length=1, default='n' ,choices=ALCOHOL) starter = models.TextField(max_length=350, blank=True, default='') main_menu = models.TextField(max_length=350, blank=True, default='') dessert = models.TextField(max_length=350, blank=True, default='') notes = models.TextField(max_length=350, blank=True, default='') created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) here is my bookings model class Bookings(models.Model): OPTIONS_STATUS = (('y', "Yes"), ('n', "No"), ('p', "Pending"),) user = models.ForeignKey(User, on_delete=models.CASCADE) event = models.ForeignKey(Events, on_delete=models.CASCADE) eventdate = models.DateField() event_amount = models.CharField(max_length=50, blank=True, default='') guests = models.IntegerField() bookingstatus = models.CharField(max_length=50, default='p', blank=True, choices=OPTIONS_STATUS) created_date = models.DateTimeField(auto_now_add=True) modified_date = … -
Django's cache clear function does not work on view cache?
I am using the view cache for Django 1.10. But I am having problems clearing the cache. @cache_page(60 * 30, cache="container_table") def container_table(request, dataset): # determine container_list by a query to the database return render(request, 'container_table.html',{"container_list":container_list}) Then container_table.html creates a table involving container_list and each row has an element of container_list along with a little checkbox. When the checkbox is checked, I want the cache to clear. So essentially when the checkbox is checked, an ajax call is made to a view that does caches["container_table"].clear(). From the django docs, this should clear ALL keys in that cache, but it is not working because when I refresh the page for container_table.html it is still using a cache. Am I misunderstanding the usage of caches["container_table"].clear()? I thought it would clear everything! -
Django/Nginx DisallowedHost header error
There are several of these threads, but none of them have an answer to my problem. I have a server hosting a website that is working perfectly if you direct there via the ip address, however I bought a dns, and I am trying to redirect the dns to the ip. I am using django 1.11.4 (the current pip install version). After setting up all of my DNS servers I can ping the server, but if I go to a browser and type in my dns I receive this error: Environment: Request Method: GET Request URL: http://thefelpub.com/ Django Version: 1.11.4 Python Version: 2.7.12 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pub') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware') Traceback: File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _legacy_get_response 244. response = middleware_method(request) File "/usr/local/lib/python2.7/dist-packages/django/middleware/common.py" in process_request 57. host = request.get_host() File "/usr/local/lib/python2.7/dist-packages/django/http/request.py" in get_host 113. raise DisallowedHost(msg) Exception Type: DisallowedHost at / Exception Value: Invalid HTTP_HOST header: 'thefelpub.com'. You may need to add u'thefelpub.com' to ALLOWED_HOSTS. I have added my dns to the ALLOWED_HOSTS=[] list, but no matter how many variations of the dns I try (including '*') I get the same error … -
Getting model filters to show count of active values
I have 2 models that are connected. Model 1 is userprofiles and model 2 is events each user can have multiple events... each event can be active or deactivated. I have a for loop in the template showing all the userprofiles... but I also want to show how many active events each user has. ANY help please my code today = datetime.now().strftime('%Y-%m-%d') perm = Permission.objects.get(codename='chef_user') user_profiles = User.objects.filter(profile__user_profile_active='y').filter(is_active=True).filter(Q(groups__permissions=perm) | Q(user_permissions=perm)).distinct()[:6] in the template I have my loop {% for kitchen_list in user_profiles %} -- CODE -- {{ kitchen_list.events_set.count }} <--- WHERE I AM TRYING TO SHOW ACTIVE EVENTS COUNT --CODE-- {% endfor %} -
issues installing postgis in django 1.11
I have been trying to install Postgis for a geodjango projec. I keep running into this error: django.core.exceptions.ImproperlyConfigured: 'django.contrib.gis.db.backends.postgis' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' Error was: cannot import name 'GDALRaster' I have tried updating the gdal and but when it runs it i get this error: building 'osgeo._gdal' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools Here is the full traceback: C:\Users\Janet\Desktop\roote>python manage.py runserver Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000001CA12A64C80> Traceback (most recent call last): File "C:\Users\Janet\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\utils.py", line 115, in load_backend return import_module('%s.base' % backend_name) File "C:\Users\Janet\AppData\Local\Programs\Python\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "C:\Users\Janet\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\gis\db\backends\postgis\base.py", line 7, in <module> from .operations import PostGISOperations File "C:\Users\Janet\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\gis\db\backends\postgis\operations.py", line 7, in <module> from django.contrib.gis.gdal import GDALRaster ImportError: cannot import name 'GDALRaster' During handling of the above exception, another exception occurred: Traceback (most recent call … -
Redundant Join Table with Django Generic Relations
I am struggling with the optimal database design for the project I am working on. I have the following models, which represent Song, Upload, and Profiles. Uploads are processed async, and there is a callback form the worker that contains the id of the upload that was processed. An Upload can be any file type, but certain files are processed differently. I was looking at inverting the relationships, and making Uploads contain the generic relationship, but it makes my serializers and validation more difficult. So opted to have foreign keys to uploads instead. Uploads can also be created prior to a Song. An upload is associated with a upload event, which can be initiated before a Song form is complete. This is similar to youtube or soundcloud where you can initiate an upload, continue with the form, and then ultimately cancel before completing the form of the video or song or save. This is also why I can't use generic relations on Uploads because I would need a nullable foreign key in the cases where uploads are created first. I need to be able to get the child object of the upload, and the field. The only way I have … -
Why do python and py commands run different python 3 versions?
I've installed django using the pip command (pip install Django), but i can't run it using the py command, as it can't find the module. I can only make it works using 'python' command. Here is a summary of the screenshot I have atttached $ python --version Python 3.6.1 $ py --version Python 3.6.0 It also looks like django works only with 3.6.1. Is there any way to set both commands to run newest version of python? screen -
Make my Django app into a rentable service for companies
I have a webapp running with Django. I would like to make an Enterprise Edition of this website. In exchange for a yearly fee, I would like to allow companies to host the webapp on their own server and benefit from unique features The problem is that I have no idea how to proceed. How can I execute this, without sending my whole code over to their computer and launching the django app there? Is there something like generating an .exe that would run the django app without sending my code? How do companies usually proceed to make their tools available on another company's intranet? -
Trying to understand how a Django foreign key works
So I'm building my first Django project now, a two-player chess website. I'm almost done and now I'm writing the tests. The project has two original models: Player and Game. The Player model has a one to one field to the User model, Player.user, and a foreign key to Game, Player.current_game, which indicates the game instance the player is currently in. The Game.draw_offered CharField takes the values "" (the default value), "w", or "b", indicating whether a draw has been offered and the color of the player who offered it. I have a test case that does the following: class Draw_ViewTestCase(TestCase): def setUp(self): self.user1 = User.objects.create_user(username="Test_User_1", password="test1") self.user2 = User.objects.create_user(username="Test_User_2", password="test2") self.factory = RequestFactory() self.game = Game.objects.create() self.player1 = Player.objects.create(user=self.user1, current_game=self.game, color="w") self.player2 = Player.objects.create(user=self.user2, current_game=self.game, color="b") def test_draw(self): request = self.factory.get(reverse('draw')) request.user = self.user1 #The draw view changes the draw_offered field of the player's current game to the player's color, and saves the current_game to the database response = draw(request) self.game.refresh_from_db() assert self.game.draw_offered == self.player1.color assert self.game == self.player2.current_game #self.player2.current_game.refresh_from_db() assert self.game.draw_offered == self.player2.current_game.draw_offered All the assertions pass but the last one, but if you uncomment the second to last line, it passes. What's going on? As I understand … -
Get total number of orders per month and the total quantity ordered per month in django ORM
I have the following two models: class Order(models.Model): set_on=models.DateField() class Details(models.Model): order=models.ForgienKey(Order,related_name='order_detail') quantity=models.IntegerField() item=models.CharField() And the data now is: id set_on 1 2017-07-01 2 2017-07-10 3 2017-08-01 4 2017-09-01 and details: id order_id quantity item 1 1 10 box 2 1 11 pens 3 3 5 box The desird output is now: period total orders total quantity 07/2017 2 21 08/2017 1 5 09/2017 1 0 In 07/2017, 2 orders were made with a total quantity of 21. This is what I have so far. It brings quantities Ok but total orders made is always equal to the highest. i.e. 2 in the above even for months 8 and 9 when the total number of orders started were 1 only. data=Order.objects.all().annotate( mon=Extract('set_on','month'),yr=Extract('set_on','year')).values('mon','yr').annotate(total_orders=Count('mon','yr'),total_quantity=Sum('order_detail__quantity')) How can i fix it to get the desired output? -
Pagination and get parameters
Django 1.11.4 I have build a search form with method="get". Search form has a lot of forms. Then this input values are transmitted as get parameters in url. The problem is how to get pagination. The database contains thousands of objects. Pagination is necessary. This is what the documentation tells us: https://docs.djangoproject.com/en/1.11/topics/pagination/#using-paginator-in-a-view It suggests like this: <a href="?page={{ contacts.previous_page_number }}">previous</a> But this will ruin all the get parameters. What I have managed to invent is: <a href="{{ request.get_full_path }}&page={{ object_list.previous_page_number }}">previous</a> This works. But this is goofy. If one switches pages forward and backward, it produces urls ending like this: page=2&page=3&page=2 I have had a look at how Google managed this problem. In the middle of the url they have start=30. And change this parameter: start=20, start=40. So, they switch. Could you help me understand how preserve get parameters and switch pages in Django? In an elegant way, of course. -
Can't access the Django server at http://127.0.0.1:8000/
At firt time it worked totally fine but it is showing this issue now: app$ python manage.py runserver Performing system checks... System check identified no issues (0 silenced). September 03, 2017 - 17:28:43 Django version 1.11.4, using settings 'aggregator.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. It says its running but I can't Access it on that address. What could have been possibly wrong? -
Access Django Rest Framework API using Javascript - getting a Token
I have an API setup using Django Rest Framework. It works fine when accessing via cURL or HTTPie or even the browsable API. The API has token authentication so initially you have to supply credentials which will return a token. Using HTTPie (or even curl) you would do this: http POST http://127.0.0.1:8000/api/v1/api-token-auth/ username="user1" password="testpassword" This would return a response e.g.: HTTP/1.0 200 OK Allow: POST, OPTIONS Content-Type: application/json Date: Sun, 03 Sep 2017 16:57:38 GMT Server: WSGIServer/0.2 CPython/3.6.1 X-Frame-Options: SAMEORIGIN { "token": "fgfdgfdgfdgfdgd45345345lkjlj" } You would then take the token and perform a GET/PUSH/etc like so: http --json POST http://127.0.0.1:8000/api/v1/test/ test_text="Testing" 'Authorization: Token fgfdgfdgfdgfdgd45345345lkjlj' I have been Google searching for a while now and cannot find any clear answers as to how the above two lines would translate into Javascript? How do I (1) Pass through credentials to get a token; (2) Retrieve the Token; (3) Use the token to make a GET and PUSH request? -
Traceback error when reading file in python
I am currently learning Python and came across the following error: Traceback (most recent call last): File "file.py", line 22, in module for word in file.read(): File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 6552: character maps to undefined This is my code: file=open('xyz.txt') dict={} ignorelist=set( line.strip() for line in open('ignorelist')) for word in file.read(): word = word.replace(".","") word = word.replace(",","") if word not in ignorelist: if word not in dict: dict[word] = 1 else: dict[word] += 1 d=collections.Counter(dict) for word, count in d.most_common(10): print(word, ": ", count) does anyone know why this happens? thanks in advance! -
Django - Object not save date in the format i need
(Sorry for my bad English) I'm having a problem when I try to save a date but only in one model all the other models saves the date perfect. But this specific model saves mm/dd/yyyy and I need dd/mm/yyyy this is the model class CashClosing(models.Model): # Relations # Attributes - Mandatory date = models.DateField( verbose_name=_('date'), ) cash_incomes = models.DecimalField( max_digits=10, decimal_places=2, verbose_name=_('cash incomes'), ) cash_expenses = models.DecimalField( max_digits=10, decimal_places=2, verbose_name=_('cash expenses'), ) cash_diff = models.DecimalField( max_digits=7, decimal_places=2, default=0, verbose_name=_('cash difference'), ) real_cash = models.DecimalField( max_digits=10, decimal_places=2, verbose_name=_('real cash'), ) next_initial_cash = models.DecimalField( max_digits=10, decimal_places=2, verbose_name=_('next initial cash'), help_text='Ingrese aquí el monto con el que abrirá la próxima caja' ) balance = models.DecimalField( max_digits=10, decimal_places=2, verbose_name=_('balance'), ) # Attributes - Optional # Object Manager objects = managers.CashClosingManager() # Custom Properties # Methods def get_absolute_url(self): return reverse( 'cash_closings:detail', kwargs={'id': self.id} ) # Meta and String class Meta: verbose_name = _("Cash Closing") verbose_name_plural = _("Cash Closings") ordering = ('date',) This is the form class CashClosingForm(forms.ModelForm): class Meta: model = CashClosing fields = [ 'date', 'cash_diff', 'next_initial_cash', ] def __init__(self, *args, **kwargs): date = kwargs.pop('date') super(CashClosingForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout(Field('date', type='hidden', value=date)) self.helper.add_input(Submit( 'submit', 'Cerrar Caja', css_class="btn btn-primary btn-block") ) … -
Return or create a token if the user already exist? django
Is posible to return or create a token if the user already exists? I need something like this class LoginEasy(CreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer def post(self, request): pw = '!Rd5tkis-02kjWk' serialized = UserSerializer(data=request.data) if serialized.is_valid(): u = User.objects.filter(email=serialized.data['email']) if len(u) > 0: userdata= {'id': u[0].id, 'password': pw, 'first_name': u[0].first_name, 'last_name': u[0].last_name, 'email': u[0].email}, token, created = Token.objects.get_or_create(user=userdata) return Response({'token': token.key, 'id': userdata.id, 'first_name': userdata.first_name, 'last_name': userdata.last_name, 'email': userdata.email}) I'm getting this error. int() argument must be a string, a bytes-like object or a number, not 'dict' -
csrf_exempt not working, unable to retrieve csrf token from Set_Cookie
I have a web page running sailsjs and javascript, users will log in to my webpage with a username and password, and i wish to programatically use this username and password to log in to another webpage which is loaded into my iFrame. The other web page is running on django. I run into 2 problems: django requires csrf token, i tried using csrf_exempt on the other webpage's login_view but it doesnt seem to work As per another stackoverflow question, it was recommended that the csrftoken may be retrieved by first doing a GET request, which the csrf token will be returned in the response header under "Set_Cookie", which can then be used to POST to django. Problem is the cookie isn't set and "Set_Cookie" is a protected header: https://bugs.chromium.org/p/chromium/issues/detail?id=56211 Is there any way i can possible retrieve the csrftoken from "Set-Cookie" response header? And why is csrf_exempt not working? I followed this link: How to exempt CSRF Protection on direct_to_template. I modified it to url(r'^login/&', csrf_exempt(login_view), name='login_view') I understand that the auth is a django code which authenticates users by creating a session, did i do something wrong in this line of code? These seems very confusing to me. -
Reverse not found in Django
This might be a simple one but I have been on this for hours, I must be missing something. Here we go: urls.py: urlpatterns = [ # Event patterns url('^$', views.BuddyProgram.as_view(), name='buddy_program'), url('^dashboard/$', views.BuddyDashboard.as_view(), name='buddy_dashboard'), url('^thank-you/$', views.BuddyFinal.as_view(), name='final'), url('^completed_intro/$', views.CompletedIntro.as_view(), name='buddy_completed_intro'), url('^completed_passive_track/$', views.CompletedPassiveTrack.as_view(), name='buddy_completed_passive_track'), url('^about/$', views.BuddyAbout.as_view(), name='buddy_about'), url('^list/$', views.Buddies.as_view(model=BuddyProfile), name='buddies'), url('^signup/$', views.BuddySignupView.as_view(), name='buddy_signup'), # url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'), url(r'^(?P<buddy_id>[0-9]+)/$', views.Buddy.as_view(model=BuddyProfile), name='buddy'), ] views.py: class BuddyFinal(TemplateView): template_name = 'buddy/thank_you.html' class BuddySignupView(SignupView): template_name = 'buddy/buddy_create.html' success_url = reverse('final') # profile specific success url form_class = BuddySignupForm profile_class = BuddyProfile # profile class goes here def form_valid(self, form): response = super(BuddySignupView, self).form_valid(form) profile = self.profile_class(user=self.user) profile.save() return response and the error I get: django.core.urlresolvers.NoReverseMatch: Reverse for 'final' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] -
Django, Can't get delete button to work
I have a section of my site where an admin can add a widget. However the delete button to delete any current widgets is not working. I have this code implemented else where on my site and it is working. I copied the same code from the other section of my site where this is being used. The other section of my site which uses this code is a little different in that a post can only be deleted be the user who created it, and the widgets can be delete by any user with the "access_level" field is equal to "admin". However, I am the only admin so it should still work. The page that the widget stuff is displayed on is only accessible if your "access_level" is equal to admin so I don't need to validate whether or not they have the permission before deleting. Please help. widget_list.html: {% extends "base.html" %} {% block content %} <div class="container"> <div class="content"> <div class="widgets-list"> {% for widget in widget_list %} <h3>{{ widget.name }}</h3> <h3>{{ widget.widget_order }}</h3> <div> <p>{{ widget.body }}</p> </div> {% if user.is_authenticated %} <a class="auth-user-options" href="{% url 'adminpanel:delete-widget' pk=widget.pk %}">Delete</a> {% endif %} {% endfor %} </div> </div> … -
Djnago says port is already in use
When I run the runserver commnd in djnago it shows port is already in use. So everytime i need to kill the process that uses the port evrytime and run the server agian Can anyone give me permanent solution to this? Thank you in advance