Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How could i get over NoReverseMatch at /polls/reset-password/ error to continue in making password resetting?
My urls.py is this and even though i have created the password-reset-done url from django.conf.urls import url from .import views from django.conf.urls import url from django.contrib.auth.views import login, logout, password_reset, password_reset_done, password_reset_confirm, password_reset_complete urlpatterns= [ url(r'^$',views.index, name= "index"), #127.0.0.1/polls url(r'^(?P<question_id>[0-9]+)/$', views.detail, name= "detail"), #127.0.0.1/polls/1 url(r'^(?P<question_id>[0-9]+)/results$', views.results, name="results"), #127.0.0.1/polls/1/results url(r'^(?P<question_id>[0-9]+)/vote$', views.vote, name="vote"), #127.0.0.1/polls/1/vote url(r'^login/$', login, {'template_name': 'polls/login.html'}), url(r'^logout/$', logout, {'template_name': 'polls/logout.html'}), url(r'^register/$', views.register, name= 'register'), url(r'^profile/$', views.view_profile, name= 'profile'), url(r'^edit_profile/$', views.edit_profile, name= 'edit_profile'), url(r'^change-password/$', views.change_password, name='change_password'), url(r'^reset-password/$', password_reset, name='reset_password'), url(r'^reset-password/done/$', password_reset_done, name='password_reset_done'), ] I am getting the following error. -
Django - cannot import name path
So i'm starting to use Django but i had some problems trying to run my server. I have two versions of python installed. So in my mysite package i tried to run python manage.py runserver but i got this error: Unhandled exception in thread started by <function wrapper at 0x058E1430> Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\Python27\lib\site-packages\django\core\management\base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "C:\Python27\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Python27\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_config return check_resolver(resolver) File "C:\Python27\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver return check_method() File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 254, in check for pattern in self.url_patterns: File "C:\Python27\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Python27\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python27\lib\site-packages\django\urls\resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) File "C:\Users\Davide\Desktop\django-proj\mysite\mysite\urls.py", line 17, in <module> from django.urls import path ImportError: cannot import name path Is it because i have two versions installed? -
Django stuck on login page
I'm very new to Django and I am trying to create an Inventory app. The front page should be a login page and after login it should get data from the Model that I created through admin, But after running server it keeps heading back to login page all the time. My Inventory(Project)- urls.py from django.conf.urls import url,include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^myapp/', include('myapp.urls')), url(r'^home/', include('myapp.urls')), ] My myapp urls.py- from django.conf.urls import url from . import views from django.contrib.auth.views import login urlpatterns = [ url(r'^home/$', views.home, name='home'), url(r'^$', login, {'template_name': 'myapp/login.html'}), ] and in my setting.py of Project- LOGIN_REDIRECT_URL = 'home/' After logging in it keeps going back to login page only! -
What is the best way to implement persistent data model in Django?
What I need is basically a database model with version control. So that every time a record is modified/deleted, the data isn't lost, and the change can be undone. I've been trying to implement it myself with something like this: from django.db import models class AbstractPersistentModel(models.Model): time_created = models.DateTimeField(auto_now_add=True) time_changed = models.DateTimeField(null=True, default=None) time_deleted = models.DateTimeField(null=True, default=None) class Meta: abstract = True Then every model would inherit from AbstractPersistentModel. Problem is, if I override save() and delete() to make sure they don't actually touch the existing data, I'll still be left with the original object, and not the new version. After trying to come up with a clean, safe and easy-to-use solution for some hours, I gave up. Is there some way to implement this functionality that isn't overwhelming? It seems common enough problem that I thought it would be built into Django itself, or at least there'd be a well documented package for this, but I couldn't find any. -
Tensorflow error while restoring multiple models on a parallel thread
I needed to consume TensorFlow models via an API. For that I wrote the API on Django. This API was supposed to receive parallel requests so I looked around and hosted it with Apache. When I consume the API one request at a time for any model, it works as expected with respect to classification tasks. However, when the requests are made to different models in a parallel manner, it starts throwing errors. Going through the error logs I believe the cause is that, the session for one of the model is loading while the session of other model is still active. Is there any way to resolve the conflict amongst these sessions? DISCLAIMER: I am a novice when it comes to web technologies(something I am learning). :) Error Logs: NotFoundError at /nlc/classify/ Key rnn/gru_cell/gates/kernel/Adam_1 not found in checkpoint [[Node: save/RestoreV2_31 = RestoreV2[dtypes=[DT_FLOAT], _device="/job:localhost/replica:0/task:0/device:CPU:0"](_arg_save/Const_0_0, save/RestoreV2_31/tensor_names, save/RestoreV2_31/shape_and_slices)]] Caused by op 'save/RestoreV2_31', defined at: File "/var/www/python/project-new-server/project-new/lib/python3.5/site-packages/django/core/handlers/wsgi.py", line 146, in __call__ response = self.get_response(request) File "/var/www/python/project-new-server/project-new/lib/python3.5/site-packages/django/core/handlers/base.py", line 81, in get_response response = self._middleware_chain(request) File "/var/www/python/project-new-server/project-new/lib/python3.5/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/var/www/python/project-new-server/project-new/lib/python3.5/site-packages/django/utils/deprecation.py", line 95, in __call__ response = self.get_response(request) File "/var/www/python/project-new-server/project-new/lib/python3.5/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/var/www/python/project-new-server/project-new/lib/python3.5/site-packages/django/utils/deprecation.py", line … -
How can i register an admin class without any model?
I want to create a class in django admin from where, i can redirect to a perticular url. I dont want to display any django admin form or any list display and so i dont want to register it with any model. Is there any way to create a class in django admin without any model. thanks in advance -
Offline installation of Django
As in: Can I install Django as offline in Windows 7? ... I am trying to install Django from a file. My RHEL 7 is in a closed network. From another computer I have fetched version 2.0.1 from https://github.com/django/django/releases. running install-command results in: pip3.6 install django-2.0.1.tar.gz Processing ./django-2.0.1.tar.gz Collecting pytz (from Django==2.0.1) Could not fetch URL https://pypi.python.org/simple/pytz/: There was a problem confirming the ssl certificate: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777) - skipping Could not find a version that satisfies the requirement pytz (from Django==2.0.1) (from versions: ) No matching distribution found for pytz (from Django==2.0.1) The error corresponds to the fact, that my system does not have access through the proxy. How can I do the install without the need of access to outside world? -
How to make django database such that the new objects will get id (last object's id +1) rather than (last deleted object's id+1)?
I'm writing a django website with a sqlite database, I have a model in my website like this : class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) Suppose I create Question object "What's up" and delete it and now create another Question object "HI" then "Hi" will get the id 2 not 1.But I want it to be 1 only.Is this possible? I m using django 1.8.7 and can't change the version as whole database is written in django 1.8.7. >> f = Question(question_text="What's up",pub_date=timezone.now()) >> f.id 1 >> f.delete() >> g = Question(question_text="Hi",pub_date=timezone.now()) >> g.id 2 Any help will be appreciated.Thanks in advance -
Count elements of list from queryset
I get a queryset from a model that saves the data to a charfield. The charfield is displayed on a form as MultipleChoiceField with a CheckboxSelectMultiple widget. The max amount of choices is 5. I want to count the number of elements in the queryset. Each queryset can vary in the amount of the elements in the list. Now, when I get len of the list, the value is 5 times the amount of elements. Is the list in the dict not a list but something else? When I create a list manually without the queryset and get len of said list, the value is correct. E.g. list with 3 elements returns 3. query = MyModel.objects.all().values('myvalue') print(query[0]) {'myvalue': "['3']"} print(query[1]) {'myvalue': "['1', '4']"} print(query[0]['myvalue'] ['3'] print(query[1]['myvalue'] ['1', '4'] print(len(query[0]['myvalue'])) 5 print(len(query[1]['myvalue'])) 10 -
Rollbar and celery causing crash onrunning django project
I'm trying to debug a problematic error which occurs when I'm trying to launch django project in which I'm using (among others) celery and rollbar. The problem occurs when I change logging level for mail_admins from ERROR to WARNING. Complete traceback is below: (env)root@test:/var/www/papukurier_test# ./manage.py migrate 2018-01-30 13:30:52 [16517] [WARNING] pathname=/var/www/papukurier_test/env/local/lib/python2.7/site-packages/rollbar/__init__.py lineno=292 funcname=init Rollbar already initialized. Ignoring re-init. Traceback (most recent call last): File "./manage.py", line 13, in <module> execute_from_command_line(sys.argv) File "/var/www/papukurier_test/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/var/www/papukurier_test/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute django.setup() File "/var/www/papukurier_test/env/local/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/var/www/papukurier_test/env/local/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/var/www/papukurier_test/env/local/lib/python2.7/site-packages/django/apps/config.py", line 120, in create mod = import_module(mod_path) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/var/www/papukurier_test/courier/apps.py", line 4, in <module> from courier.api.consumers import INIT_COURIERS_CONSUMERS_SIGNATURE File "/var/www/papukurier_test/courier/api/consumers.py", line 10, in <module> from papukurier.celery import celery_app File "/var/www/papukurier_test/papukurier/celery.py", line 23, in <module> rollbar.init(**settings.ROLLBAR) File "/var/www/papukurier_test/env/local/lib/python2.7/site-packages/rollbar/__init__.py", line 292, in init log.warning('Rollbar already initialized. Ignoring re-init.') File "/usr/lib/python2.7/logging/__init__.py", line 1164, in warning self._log(WARNING, msg, args, **kwargs) File "/usr/lib/python2.7/logging/__init__.py", line 1271, in _log self.handle(record) File "/usr/lib/python2.7/logging/__init__.py", line 1281, in handle self.callHandlers(record) File "/usr/lib/python2.7/logging/__init__.py", line 1321, in callHandlers hdlr.handle(record) File "/usr/lib/python2.7/logging/__init__.py", line 749, in handle self.emit(record) File "/var/www/papukurier_test/env/local/lib/python2.7/site-packages/django/utils/log.py", line 119, in emit message = … -
Django filtering relationship table
I'm trying to do a for loop that displays the items in one of the foreign key fields after using another foreign key filter. I'm getting this message: One matching query does not exist. Models.py class One(models.Model): description = models.TextField(blank=True) function = models.ForeignKey(Function, related_name='program', blank=True) program = models.ForeignKey(Program, related_name='function', blank=True) def __unicode__(self): return "description{}, function{}, program{}".format(self.description,self.function,self.program) class Program(models.Model): title = models.CharField(max_length=255) def __unicode__(self): return "title{}".format(self.title) Views.py def function_page(request, Function_id): assignments = Function.objects.get(id=Function_id) func_programs = One.objects.get(function=Function_id).program.all( context = { 'func_programs' : func_programs } return render (request, 'project/function.html', context) HTML <select id=options name="func_programs"> <option>Choose From List</option> {% for func_program in func_programs %} <option value="{{func_program.function.id}}"> {{func_program.program.title}}</option> {% endfor %} </select><br> How can I filter this so that my scroll down shows the program title of all the programs under one particular function? Thanks in advance. -
Django - DB existing field add to model
I have a model SomeObject without field type, but data is already in DB. How can I insert type ForeignKey to SomeObjectType model into SomeObject to get as the result the field type. type field is not nullable and has no default value. -
mezzanine popup not closing
I have 3 models Company,Contacts,CompanyAssociation. Contacts has a m2m realtion with CompanyAsso. And CompanyAss. has a foriegn key relation with Company.Now In the admin panel when I try to add new contact and i click + on m2m field it opens a popup and shows CompanyAss. model when i click on + of froeign key relation it takes me to Company model.I add the data and click save then the popup does not close.The data does get save. What i want is when the company is added it should take me Back to CompanyAssoc model.. -
Struggling to display a modelForm in admin panel
Im trying add custom ModelForm to Django admin panel, however I am getting this error. django.core.exceptions.FieldError: Unknown field(s) (tron, rchain, etc..) I want to have a form in admin-panel when you click add to 'Currencies' there will be a choice of currencies and you can select one. I have been tweaking it for a while and can not come up with a solution. Basically, i believe I need to create a model instances 'on the go' whenever I select a currency in the admin panel.But how do I achieve it ? My code below #modelForm.py class Currencies_Form(ModelForm): #tuplez = [(i,) for i in Coins.arr] cryptoId = forms.ChoiceField(choices=Coins.arr, initial=' ', widget=forms.Select()) class Meta: model = Currencies fields = Coins.arr models.py class Currencies(models.Model): cryptoId = models.CharField(max_length=50) cryptoPrice = models.CharField(max_length=50) My file with an api call and data - CoinAPI.py class Coins: def __init__(self): self.arr = [] self.hashTable = {} params = 100 data = requests.get('https://api.coinmarketcap.com/v1/ticker/?limit={}'.format(params)).json() for objects in data: for k in objects.keys(): if k == 'id': self.arr += objects[k].split() self.hashTable.update({objects[k]:objects['price_usd']}) Coins = Coins() and my admin.py class whatever(admin.ModelAdmin): form = Currencies_Form admin.site.register(Currencies,whatever) Please don't mind the naming, clearly not PEP-8 standard, it's just for my local testing yet. -
Config RegexField's just accept hyphen (-) and numbers only - Django Rest Framework
Hope your guys help me Config RegexField's just accept hyphen (-) and numbers only in Django Rest Framework Now I config: username = RegexField(regex=r'^[a-zA-Z0-9]+$', required=True, max_length=50) It's not work! Thanks in advance! -
Django_permissions, how to template my menu item based on the permissions?
I want to display menu item based on my given permissions, for example users who are not a Project manager thex dont see item project in the menu and so on.. I have a separated Client dashboard from admin dashboard which is not so good and pro. Here my code: models.py class Customer(models.Model): birthday= models.DateField(blank=True, null=True) address= models.CharField(max_length=50, blank=True, null=True) auth_user = models.ForeignKey(to=User) class Meta: db_table = 'Customer' permissions = (("view_user", "Can_view_user"),) views.py class UsersListView(PermissionRequiredMixin, LoginRequiredMixin, ListView): login_url = 'accounts/login/' permission_required = 'can_view_user' template_name = "user_list.html" model = User def dispatch(self, request, *args, **kwargs): if check_permission_BM_or_AM(request): if request.user.is_authenticated(): return super(UsersListView, self).dispatch(request, *args, **kwargs) return redirect_to_login(self.request.get_full_path(), self.get_login_url(), self.get_redirect_field_name()) permission.py def check_permission_BM_or_AM(request): customer= Customer.objects.get(auth_user_id=request.user.id) marolle = MaRolle.objects.filter(ma=customer.id) rollen = Rollen.objects.get(id=1) rollens = Rollen.objects.get(id=4) for ma in marolle: if str(ma.rolle) == rollen.rolle or str(ma.rolle) == rollens.rolle: return True def check_permission_AM(request): customer= Customer.objects.get(auth_user_id=request.user.id) marolle = MaRolle.objects.filter(ma=customer.id) rollens = Rollen.objects.get(id=4) for ma in marolle: if str(ma.rolle) == rollens.rolle: return True menuitem.html <ul> <li class="dropdown-submenu "> {% if can_view_user%} <a tabindex="-1" href="/user/list/"><span class="fa fa-fw fa-book "></span> Users</a> {% endif %} </li> view.py (my_app) @login_required(login_url="/accounts/login/") def index(request): if request.user.is_superuser: return HttpResponseRedirect('/administrator/') elif request.user.is_active and request.user.is_authenticated: return HttpResponseRedirect('/user/') views.py(user) class UsersListView(PermissionRequiredMixin, LoginRequiredMixin, ListView): login_url = 'accounts/login/' permission_required = … -
Define Django variable in statement
I want to define a variable in my Django template but if I set the variable within the statement I can't call it again. Is there any way to call the variable from the other part of my template? Thank you in advance! My attemt: {% if a > 1 %} {% with "string_1" as var %} {% endwith %} {% elif a < 1%} {% with "string_2" as var %} {% endwith %} {% else %} {% with "string_3" as var %} {% endwith %} {% endif %} {% if var='string_1' %} #here i want to call the variable again <p>This is string_1</p> {%else%} <p>This is not string_1</p> -
Personally identifying data in Django Request
I was working on a Django project which had no user data logging. Then I added IP Address and User Agent logging for posts. What other personally identifying do I get other than IP Address and User Agent in a Django request in the view. I don't want to log too much. The above two should be enough. But I just want to know if there is any other good information to log about the user. -
Delete record without accessing it directly
I am creating a data visualisation site in django and using the rest api for my data. Is there any way of deleting a record without accessing its url directly, as in this case it is impossible. Something like def employee_delete(request): instance = Employee.objects.get(social_security=request.POST) instance.delete() return render(request, "dashboard.html") This only works if you have access to the console as I learned, so I tried to access the data from a form like so def employee_delete(request): if request.method == "POST": form = delete_EmployeeForm(request.POST, request.FILES) if form.is_valid(): instance = Employee.objects.get(social_security=request.POST) instance.delete() return render(request, "dashboard.html") else: form = delete_EmployeeForm() return render(request, "deleteemployee.html",{'form': form}) Would this work if I was able to be more specific about which piece of data I was accessing from the form? I got a typeError trying to use request.Post in that manner. That form contained a single field in 'social_security' from the Employee model. Thanks -
How to implement method in Django REST?
Have the next Django REST question. I have the view. class MessageViewSet(viewsets.ModelViewSet): serializer_class = MessageSerializer queryset = Message.objects.filter(isread = False) def mark_read(): queryset = Message.objects.update(isread=True) return Response({'read':queryset}) And router in urls.py router = SimpleRouter() router.register(r'api/get_messages', MessageViewSet) urlpatterns = [ url(r'^$', MainView.as_view(), name='main'), url(r'^', include(router.urls)) ] Now i have 'get_messages' page which shows all list. How can i implement a method which would change 'isread' value of model instanse from False to True, when I visit a 'mark_read' page? As you can see, i tried to write method in the class. But when i'm trying to call it in urls in this way: router.register(r'api/mark_read', MessageViewSet.mark_read), Here comes an error. assert queryset is not None, 'base_name argument not specified, and could ' \ AssertionError: base_name argument not specified, and could not automatically determine the name from the viewset, as it does not have a .queryset attribute. Maybe i shouldnt use router, and rewrite view and urls in other way. If u know how to solve this problem, please answer. Thanks. -
django haystack (solr backend) index only data after specific date
I am trying to index only data after specific created date, not all records of the model with django haystack. Originally I thought that index_queryset() method is used when executing index_update and/or rebuild_index. So I tried to add created__lte=(current_date) and I was wrong it always get all records of the model to index them -
Djangocms with Vue.js frontend
Recently came across these repositories on Github: https://github.com/dreipol/djangocms-spa https://github.com/dreipol/djangocms-spa-vue-js If anyone has used these before please help me with the initial setup. -
TypeError: TypeError("object of type 'NoneType' has no len()",) while convert pdf to image
I am building API which converts uploaded pdf to image based on Django REST framework, on MacOS env. Of course, installed imagemagick and ghostscript well. Here is my code snippet. try: with Image(filename=pdffile, resolution=300) as img: for i, page in enumerate(img.sequence): filename = '{}-{}.jpg'.format(imagefilename, i + 1) file ='{}/{}'.format(tmp_dir, filename) Image(page).save(filename=file) filelist.append(filename) except WandException as e: print e except TypeError as e: print e But I am getting this error: Exception TypeError: TypeError("object of type 'NoneType' has no len()",) in > ignored At the line: with Image(filename=pdffile, resolution=300) as img: I googled this problem, but couldn't find out correct solution. Most of them say like this: Re-install imagemagick. Check system environment path variable. These solutions don't work for me. Have you ever faced issues like this? Have any other solutions? -
Rollup in Django ORM
Is it possible to use ROLLUP aggregation in Django ORM without writing raw SQL? -
Django-cms no reverse match using apphook from admin
i hope you can help me. I'm using django 1.11 and django-cms. I created an apphook to manage urls from a certain page. I already created the page (with all translations) and associated it with my application so everything works fine. My problem occurs when, from admin, i'm inside the change page related to an instance of a model. I see the button 'view on site' that uses an url created this way: /admin/r/content_type_id/object_id/ django.contrib.contenttypes.views.shortcut admin:view_on_site Clicking on it i get the error Reverse for 'myapp_mymodel_detail' not found Do you know the correct way to make it works?