Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
from where the "}" is coming (The current path, entries/}, didn't match any of these.) in Django
I have just started learning Django and while making an app in the link it is showing %7D and giving the error : Using the URLconf defined in ag.urls, Django tried these URL patterns, in this order: admin/ entries/ [name='list'] [name='home'] ^about/$ [name='about'] contact/ [name='contact'] The current path, entries/}, didn't match any of these. I have searched for this over the internet but I have not get the solution yet. -
Django: Adding foreign key to form -> Cannot assign "<SimpleLazyObject:, must be a "User" instance
The user is in a DetailView of a patient with a in id (parent table/model), or selects a patient to create a child (table/model) object (I hope that is accurate terminology). I'm trying to "pre-populate" my form with the correct foreign key from the parent table. Basically, Each patient will have several visits, and the visits need to have the correct foreign key relationships with the patient table ("main" model). I am getting the following error relating to my def form_valid command in the views.py file. If I remove this command I get a not null error as the field needs to be filled. I also tried get_instance function but the forums advise against this in favor of the def form_valid. Error Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x10d62d278>>": "Visit.fk_visit_user" must be a "User" instance. Request Method: POST Request URL: http://127.0.0.1:8000/clincher/visit/add/2 Django Version: 2.0.4 Exception Type: ValueError Exception Value: Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x10d62d278>>": "Visit.fk_visit_user" must be a "User" instance. Exception Location: /Users/nrsmoll/venv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py in __set__, line 197 Python Executable: /Users/nrsmoll/venv/bin/python Python Version: 3.6.4 Python Path: ['/Users/nrsmoll/PycharmProjects/clincher', '/Users/nrsmoll/PycharmProjects/clincher', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python36.zip', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload', '/Users/nrsmoll/venv/lib/python3.6/site-packages', '/Users/nrsmoll/venv/lib/python3.6/site-packages/setuptools-28.8.0-py3.6.egg', '/Users/nrsmoll/venv/lib/python3.6/site-packages/pip-9.0.1-py3.6.egg', '/Applications/PyCharm.app/Contents/helpers/pycharm_matplotlib_backend'] Server time: Wed, 6 Jun 2018 13:16:29 +0000 Traceback Environment: Request Method: POST Request … -
Django from dynamic data insertion
I am basically making a django form using the models given below: class DeviceType(models.Model): device_type = models.CharField(max_length=200,unique=True) class Device(models.Model): device_type = models.ForeignKey(DeviceType,to_field='device_type') serial_number = models.CharField(max_length=200,unique=True) in_use_by = models.ForeignKey(User,to_field='username') brand = models.CharField(max_length=200,default="-", null=False) model = models.CharField(max_length=200,default="-", null=False) type_number = models.CharField(max_length=200,blank=True,null=True) mac_address = models.CharField(max_length=200,blank=True,null=True) class Repair(models.Model): device_type = models.ForeignKey(DeviceType,to_field='device_type') submitted_by = models.ForeignKey(User,to_field='username') comments = models.TextField() repair_request_date = models.DateField(default=datetime.now) repair_status = models.ForeignKey(RepairStatus, to_field="repair_status", null=True) repair_cost_estimate = models.FloatField(null=True) My devicetype option contains the following values: Dongle Charger Desktop Power Cord Laptop Charger Dongle Keyboard Mouse Desktop Laptop Now, suppose a particular user possesses only laptop and mouse. If he clicks for repair device option in my main form then, according to the models, the form will display all the values of the devicetype in the dropdown. What I want is, the dropdown must display only laptop and mouse i.e. only those devicetype that are associated with a particular user. How can i achieve this? Requesting help at the earliest. -
Can't `pip3 install -r requirement.txt`
I'm getting dependency error while installing dependency for django project Here is my part of requirement file social-auth-app-django==1.2.0 social-auth-core==1.7.0 ... stream-django==1.4.0 .. PyJWT==1.3.0 .. without pyJWT == 1.3.0 line, stream-python 2.8.1 has requirement pyjwt==1.3.0, but you'll have pyjwt 1.6.4 which is incompatible. with pyJWT == 1.3.0 social-auth-core 1.7.0 has requirement PyJWT>=1.4.0, but you'll have pyjwt 1.3.0 which is incompatible. djangorestframework-jwt 1.11.0 has requirement PyJWT<2.0.0,>=1.5.2, but you'll have pyjwt 1.3.0 which is incompatible. -
Error viewing pages/ in wagtail CMS
I started getting an error when viewing pages in wagtail cms: ProgrammingError at /cms/pages/ column "wagtailcore_page.content_type_id" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: SELECT "wagtailcore_page"."id", "wagtailcore_page"."content_... Viewing the Root CMS page seems to be fine and also editing pages. If i access a child page such as /cms/pages/6/ that works but if i view the parent /cms/pages/5/ it causes the error. Any ideas how this is happening? wagtail==1.13.1 Django==1.10.5 The page class looks like: class LandingPage(Page): body = StreamField([ ('heading', blocks.CharBlock(classname="full title")), ('rich_text', RichTextBlock()), #('image', ImageChooserBlock()), ('image_grid', ImageGridBlock()), ('two_columns', TwoColumnBlock()), ('landing_map', MapBlock()), ('video_grid', VideoGridBlock()), ('slider', SliderBlock()), ('steps', StepsBlock()), ('pricing', PricingBlock()), ('centered', RichTextBlock(template='blocks/centered.html')), ]) content_panels = Page.content_panels + [ StreamFieldPanel('body'), ] -
Django&Python, scrap page to fill up database
I've got django running with models. Now, I want that fill todatabase with information from different websites. There comes scrapping, I know. What I'm missing is knowledge if there's any tool to scrap pages with Django that gives compatibility with existing database/models? Please note that I'd like to run this scrapping task every 5 mins for example, so it won't be one-run script. Could you please point me out which tools should I use? Should I stay with Django or use something external? -
Can't install my old Django project from new mac computer
I just pulled out my old django project (I stopped developing 6 months ago). And I try to run it on my mac computer. I had weird erros such as Could not find a version that satisfies the requirement ufw==0.35 (from -r pip3_requirements_copy.txt (line 95)) (from versions: ) No matching d But I solved it by deleting that line from requirement.txt. And finally it gives me new error below build/temp.macosx-10.13-x86_64-3.6/_openssl.c:2407:14: error: typedef redefinition with different types ('void' vs 'struct comp_method_st') typedef void COMP_METHOD; ^ /usr/local/opt/openssl/include/openssl/ossl_typ.h:181:31: note: previous definition is here typedef struct comp_method_st COMP_METHOD; ^ 1 error generated. error: command 'clang' failed with exit status 1 ---------------------------------------- Command "/usr/local/opt/python/bin/python3.6 -u -c "import setuptools, tokenize;__file__='/private/var/folders/90/vbn67txd7zngjs2kzcsp73fw0000gn/T/pip-install-67i1eh50/cryptography/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /private/var/folders/90/vbn67txd7zngjs2kzcsp73fw0000gn/T/pip-record-d3q5_te0/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/var/folders/90/vbn67txd7zngjs2kzcsp73fw0000gn/T/pip-install-67i1eh50/cryptography/ I'm frustrated because this project is not working on my laptop. It used to work on ubuntu but now it's not working for some reasons. :( -
IndexError tuple index out of range
I am getting IndexError tuple index out of range the print in comment also gives ValueError malformed node or string: ['(300, 600)'] dict3={'diameter': {'attri': ['(300, 600)'], 'op': 'range'}} result = Product.objects.all() for key, value in dict3.items(): print(value['attri']) print(value['op'])#print( ast.literal_eval(value['attri'])) if value['op'] is 'range': result = result.filter(**{'attributes__{}__{}'.format(key, value['op']): ast.literal_eval(value['attri'])}) else: result = result.filter(**{'attributes__{}__{}'.format(key, value['op']): value['attri']}) print(result) -
How to exhaustively see queries Django is running?
I am optimizing a big part of my code so I am trying to reduce the database hits to the minimum and try to grab all necessary data in big but few queries and cache it. However I have not found an effective way of seeing whether Django is actually running a query against the database or whether it is returning cached or prefetched data. Ideally, I want to debug the relevant parts of my code line by line and each raw SQL queries should be displayed as they are executed. This way to check running queries suggested by the docs is not good enough, as it only displays queries formed in the same file where you access connection.queries, apparently. Accessing QuerySet.query is no good either, as it requires a, well, QuerySet object. There are other scenarios where queries are run against the database but the return type is not a QuerySet. I am not sure the Django Debug Toolbar would work either, because I don't want my behavior wrapped in a view, I want to execute an independent script and thoroughly debug it. -
Django : test with multiple patterns
I'm coding a class which is overriding DiscoverRunner (link). And i've three kind of tests : front tests called tests_front.py back tests called tests_back.py tests from different modules i'm using called tests.py My front tests are very slow, and i'd like to have a parameter to call only tests_back.py and tests.py files. The pattern i'm currently using: pattern='(*back.py|tests.py)' But this is calling any test, it looks like manage.py's pattern is not a real pattern. Ran 0 test in 0.000s Do you know how to solve my problem ? Thank you ! -
Maintaining log.django file
I have the standard django logging config in my settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'log.django', }, }, 'loggers': { 'django': { 'handlers': ['console', 'file'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'), }, }, } so it logs to log.django. However log.django is getting too big (>500k lines) so I'm wondering if it is ok to delete this file. Will the file create itself once it's deleted? I'm running django with nginx/gunicorn via digitalocean and I thought there was already a measure in place to maintain this file - but it doesn't seem to be working. -
Template not found in /admin in django
when i give the link http://127.0.0.1:8000/admin/ it is automatically redirected to http://127.0.0.1:8000/admin/login/?next=/admin/ and showing the error TemplateDoesNotExist at /admin/login/ admin/login.html Request Method: GET Request URL: http://127.0.0.1:8000/admin/login/?next=/admin/ Django Version: 2.0.6 Exception Type: TemplateDoesNotExist Exception Value: admin/login.html Exception Location: /media/nimish/WINDOWS/Users/Home/engineerbabu/user_interface/mysite/venv/lib/python3.5/site-packages/django/template/loader.py in select_template, line 47 Python Executable: /media/nimish/WINDOWS/Users/Home/engineerbabu/user_interface/mysite/venv/bin/python Python Version: 3.5.2 Python Path: ['/media/nimish/WINDOWS/Users/Home/engineerbabu/user_interface/mysite', '/media/nimish/WINDOWS/Users/Home/engineerbabu/user_interface/mysite/venv/lib/python35.zip', '/media/nimish/WINDOWS/Users/Home/engineerbabu/user_interface/mysite/venv/lib/python3.5', '/media/nimish/WINDOWS/Users/Home/engineerbabu/user_interface/mysite/venv/lib/python3.5/plat-x86_64-linux-gnu', '/media/nimish/WINDOWS/Users/Home/engineerbabu/user_interface/mysite/venv/lib/python3.5/lib-dynload', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/media/nimish/WINDOWS/Users/Home/engineerbabu/user_interface/mysite/venv/lib/python3.5/site-packages'] Server time: Wed, 6 Jun 2018 12:15:54 +0000 -
How to write the permission of a instance's user is the request.user?
How can I write the IsThePhysicalServerUser? you see my UpdateAPIView: class PhysicalServerCustomerUpdateAPIView(UpdateAPIView): """ Customer's update PhysicalServer """ serializer_class = CustomerUpdatePhysicalServerSerializer permission_classes = [IsThePhysicalServerUser] queryset = PhysicalServer.objects.all() There I want to write a permission which is IsThePhysicalServerUser. the PhysicalServer model is bellow: class PhysicalServer(models.Model): """ 实体服务器 """ name = models.CharField(max_length=32) desc = models.CharField(max_length=256, null=True, blank=True) ... user = models.ForeignKey(to=User, related_name="physical_servers", null=True, blank=True, on_delete=models.SET_NULL) I want the IsThePhysicalServerUser permission realize the PhysicalServer instance's use is the request user. How to write the permission? -
Getting model name in admin change_list_result.html
Does anyone know how to get the name of the model in the template from admin "change_list_result.html"? I need them to printing in JS. -
How to get a file from a network windows directory and move to my Python Django project directory?
I'm programming in a MacOS and using Python + Django. I must to get some files in our private network (Windows network) and move them to our server. There, Python/Django will read these files and save the data in a database. How can I do that? What I have tried source_path = "smb://server-name/GRUPOS/TECNOLOGIA_INFORMACAO/Dashboard Diretoria/" dest_path = "./static/reports/". # This is my static folder where I want to move the file file_name = "general_reports.csv" shutil.copyfile(source_path + file_name, dest_path + file_name) It gives the follow error: [Errno 2] No such file or directory: 'smb://server-name/GRUPOS/TECNOLOGIA_INFORMACAO/Dashboard Diretoria/general_reports.csv' This path (source_path) I just copied and past from the Finder, so... I think that it's correct. I have already searched at StackOverflow and I have tried other methods like put "r" before the path... Nothing.... Technologies used Python 3.6; Django 3.0.5; Mac OSX; Windows Network. Thank you for your help and patience. -
Test sending email in django from another thread
I'm trying to test my code that sends emails. More or less my unit test looks like: class EmailTest(TestCase): def test_send_email(self): my_send_mail_method() self.assertEqual(len(mail.outbox), 1) This code works perfectly fine as long as my_send_mail_method sends email in the same thread. However, when I change the code in a way that my_send_mail_method will send mail from another thread len(mail.outbox) is equal to 0. my_send_mail_method waits until the sending email is finished so I don't think it's a concurrency problem. -
Django custom user with tuple as username
I have a solid level on Django, but can't find how to solve this one properly : I created an API that will be used in multiple mobile projects. So I implemented an Application model that I pass when I log in. I also created a custom user model : class CustomUser(AbstractUser): created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) username = None email = models.EmailField('email address', unique=True) application = models.ForeignKey(Application, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() class Meta: unique_together = ('email', 'application') I'm using djangorestframework-jwt. So I've an API call that needs an email, password and an Application (apikey as a string FYI) to get a token. Everything is working fine, except that in this configuration, I'm not able to create another user with the same email but a different Application. Because my EmailField is my USERNAME_FIELD. Is there any solution that would avoid me to rewrite everything ? The best thing I have in mind is to add a field (for example a CharField) that would be unique (for example the combinaison of user.id + apikey) that would be filled automatically on creation. But then when I use ./manage.py createsuperuser, django would ask me to fill … -
Selenium Python can't connect with headless firefox
I'm using selenium in a Django app chat's tests.py tests.py from channels.testing import ChannelsLiveServerTestCase from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver import FirefoxOptions class ChatTests(ChannelsLiveServerTestCase): serve_static = True # emulate StaticLiveServerTestCase @classmethod def setUpClass(cls): super().setUpClass() try: # NOTE: Requires "chromedriver" binary to be installed in $PATH opts = FirefoxOptions() opts.add_argument("--headless") cls.driver = webdriver.Firefox(firefox_options=opts) except: super().tearDownClass() raise .... I ran the test like so and got back this error (chatenv) muiruri_samuel@train:~/webapp/chatsys$ python manage.py test chat.tests Creating test database for alias 'default'... System check identified no issues (0 silenced). E ====================================================================== ERROR: setUpClass (chat.tests.ChatTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/muiruri_samuel/webapp/chatsys/chat/tests.py", line 19, in setUpClass cls.driver = webdriver.Firefox(firefox_options=opts) File "/home/muiruri_samuel/webapp/chatenv/lib/python3.6/site-packages/selenium/webdriver/firefox/webdriver.py" , line 170, in __init__ keep_alive=True) File "/home/muiruri_samuel/webapp/chatenv/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 156, in __init__ self.start_session(capabilities, browser_profile) File "/home/muiruri_samuel/webapp/chatenv/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 245, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "/home/muiruri_samuel/webapp/chatenv/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 314, in execute self.error_handler.check_response(response) File "/home/muiruri_samuel/webapp/chatenv/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: connection refused ---------------------------------------------------------------------- Ran 0 tests in 61.180s FAILED (errors=1) Destroying test database for alias 'default'... according to what I've checked the likely cause is firefox isn't able to run headless on the vm on ubuntu since it's on a server … -
Upcomming and past items in django admin panel
I am working with django 1.11. I would like to have in the admin panel only upcoming events and those that have passed. And at the top of the page as bread crumbs links to all months - but I think it will happen automatically from django-suit. admin.py def get_queryset(self, request): currentMonth = datetime.now().month upcomming = models.Event.objects.all().order_by('event_from').filter(Q(event_from__month=currentMonth) | Q(event_from__month=currentMonth+1)) past = models.Event.objects.all().order_by('-event_from').filter(event_from__month__lt=currentMonth) return list(upcomming) + list(past) I got an error/information: Something's wrong with your database installation. Make sure the appropriate database tables have been created, and make sure the database is readable by the appropriate user. -
Can't select a row from django models to output them to third model.
I have two django models. Every model has n number of objects(rows in database). I want to select an object(a row) from model 1 and another object from model 2. I want to use fields of selected objects to create an object in model 3 using actions or otherwise. Please help me. -
Error with the template path in django 2.0
Here is my settings.py : PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. #os.path.join(PROJECT_ROOT, 'templates').replace('\\','/'), "templates", ) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIRS], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] So here is my error : Using engine django: django.template.loaders.filesystem.Loader: /home/bussiere/Workspace/Bourse/Event/('templates',)/index.html (Source does not exist) django.template.loaders.app_directories.Loader: /usr/local/lib/python3.5/dist-packages/django/contrib/admin/templates/index.html (Source does not exist) django.template.loaders.app_directories.Loader: /usr/local/lib/python3.5/dist-packages/django/contrib/auth/templates/index.html (Source does not exist) Traceback Switch t i don't understand this url : /home/bussiere/Workspace/Bourse/Event/('templates',)/index.html (Source does not exist) here is my version of django : -> % django-admin version 2.0 If you have any idea why regards -
Add an Django Admin page for a Managed=False model
I want to add a link to my Django admin page that will simply show a page with some embedded graphs from another site/app on the same server (Metabase). I have created a metabase app that has managed=False so as not to create a db table. However, I can't get this to add to the admin. Whats the best way to add this app to the admin and perhaps set it up so a default html template with my embedded iframes display ? Thanks -
Django template inner for loop works only once
my code. {% for task_in in object_list %} <time> {{task_in.id}} {%for x in data %} {{x.0}} {%if x.0 is task_in.id %} {{x.1|timesince}}&nbsp ago {% endif %} {% endfor %} </time> {% endfor %} Here the inner for loop executes only once and i don't understand where i went wrong. -
Can't override AuthenticationForm
I try to add an additional check that the user has certain text in the field, but I can not redefine the AuthenticationForm. Forms.py: from django.contrib.auth.forms import AuthenticationForm as BaseAuthenticationForm from django.contrib.auth.models import User class AuthenticationForm(BaseAuthenticationForm): print('here') or class AuthenticationForm(BaseAuthenticationForm): def clean(self): print('hi') return self.cleaned_data class Meta: model = User does not work. The feeling is that I do not get into them because the output of the line is the first command. Views.py: from .forms import AuthenticationForm def LogIn(request): if request.method == 'POST': form = AuthenticationForm(request.POST) if form.is_valid(): print('hi there') username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) login(request, user) return redirect('/') else: print(form.errors) else: form = AuthenticationForm() return render(request, 'userprocessing/login.html', {'form': form}) all print I use only to check what works. What am I doing wrong? The registration form has redefined and with the authorization of the problem. -
Unable to open popup window from django admin change view
I am trying to open a simple popup window from the Django admin change view, change_form.html(overridden) <li><a href="/admin/django_ipam/ipaddress/add/?_to_field=id&_popup=1&ip_address={{i}}&subnet={{subnet}}">{{i}}</a></li> Instead of showing a popup, it navigates to that page(looks obvious though) and upon saving the form the page is stuck as Popup closing.... What is the correct way to do this?