Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get data from model A to model B after filling the form of model B in django
I have following two models. What I want is Whenever I fill the data in model Book i.e its name (like name of Book says Java) It will automatically be saved also in Contributor model under field "name". Also I can manually be able to fill the "name" field in Contributor model in django Admin class Book(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name class Contributor(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name Data in model Book After Filling Data in model Book I want Data in model Contributor as this -
Render hyperlinks in django-wagtail template
I have a little problem, I created this model, and now I need a template for render the "related links section" in the bottom of a "post page" . class PostPageRelatedLink(Orderable): page = ParentalKey(PostPage, related_name='related_links') name = models.CharField(max_length=255) url = models.URLField() panels =[ FieldPanel('name'), FieldPanel('url'), ] I have no idea how to write html for that :) I wrote this, but obviously doesn't work <div class='related_links'> <h3>Related Links</h3> {% for item in page.related_links.all %} <a href='related_links'>{{ page.related_links.url }}</a> {% endfor %} </div> What is the right way to do this? Thanks for help! -
No exception raised when saving an empty field with null=False - Django
I have the following model: class User(models.Model): email = models.EmailField(max_length=254, null=False, unique=True) referral_code = models.CharField(max_length=10, null=False, unique=True) And used the Django shell to save a user instance with referral_code undefined: u = User(email="test@example.com") u.save() This did not raise an exception. My understanding was that null=False would require referral_code to be set - Is this not the case? How would I achieve that behaviour? -
auth.user not resolved error django
i added one field to my model and attached it to django user model through foreignkey. My model is, from django.db import models from django.contrib.auth.models import User # Create your models here. class user_files(models.Model): Filename = models.CharField(max_length=50) Browse = models.FileField() Username = models.ForeignKey(User,default=1) but while migration it is giving me error as 'valuerror: related model 'auth.user' cannot be resolved.' what does that mean and how to resolve that? I tried many things but did not work. Thanks in advance. -
Adding an image into a django template from the static folder - Django
I have a django template and I want to add an static image to the file from my static folder that I have within the applicaiton. I am trying to but nothing is appearing on the template. DOes anyone know where my error is coming from. Here is my code: {% extends "base.html" %} {% block content %} <div class="row"> <div class="col"> <img src="static/images/Artboard1.png" alt=""> <h2>{{ currentUser.username }}</h2> </div> <a href="{% url 'logout' %}">Logout</a> {% endblock %} Here is an image of my directory: -
Need Tips for Two dimensional array in Python
I am new in python. I have a two dimensional list in django. Now I want to check if given text is in list or not. But its not working. Here is my code: newmessage = 'Bye' stockWords = [ ['hello', 'hi', 'hey', 'greetings'], ['Bye', 'Goodbye'] ] for i in range(0, len(stockWords)): if newmessage.lower() in stockWords[i]: return HttpResponse('Found') else: return HttpResponse('Not Found') The problem is it works only for first element of list, the second one is not working. What am I doing wrong? Any suggestion? -
overlapping Navbar in bootstrap in a Django template
My navbar is overlapping my web, and I don't know how to change it. Now is : You can see the number of events and the blue button for create a new event, are cut in the middle by navbar. My templates are: navbar.html <div class="navbar navbar-default navbar-fixed-top" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="{% url 'events_app:panel' %}">Eventus</a> </div> <div class="collapse navbar-collapse"> <ul class="nav navbar-nav pull-right"> <li><p class="navbar-text">Bienvenido, <a href="#" class="navbar-link">{{ user.username|capfirst }}</a></p></li> <li><a href="{% url 'users_app:logout' %}">Logout</a></li> </ul> </div><!--/.nav-collapse --> </div> </div> panel.html {% block title %}Panel{% endblock title %} {% block content %} {% include "events/panel/navbar.html" %} <div class="container"> <div class="page-header "> <h4> <strong> Tienes <span class="label label-warning">0</span> Eventos disponibles </strong> <a class="btn btn-primary pull-right" href="{% url 'events_app:nuevo' %}"> <span class="glyphicon glyphicon-plus"></span> Crear un evento nuevo </a> </h4> </div><!-- page-header --> <div class="row"> <div class="col-md-12"> <table class="table table-striped table-hover"> <thead> <tr> <th colspan="2">Nombre del evento</th> <th>Categoría</th> <th>Inicio</th> <th>Fin</th> <th>Monto</th> <th class="text-center">Acciones</th> </tr> </thead> <tbody> <tr> <td> <img src="" alt="" width="60" class="img-rounded"> </td> <td>name</td> <td>category</td> <td>start</td> <td>finish</td> <td> <span class="label label-default">Gratuito</span> <span class="label label-info">S/. 0.00</span> </td> <td class="text-right"> <a href="#" class="btn btn-success"><span … -
Middleware logging limitation Django 1.11
Background: I have integration test which is working fine, but later on failed when I added the customized middleware def test_mobile_update_customer(self): user = User.objects.create(username='warhead') self.client.force_authenticate(user=user) mommy.make(Customer, family_name='IBM', created_user=self.soken_staff, updated_user=self.soken_staff) data = { "family_name": "C0D1UM" } customer = Customer.objects.first() res = self.client.patch(reverse('api:customer-detail', kwargs={'pk': customer.id}), data=data) self.assertEqual(200, res.status_code) customer.refresh_from_db() self.assertEqual('C0D1UM', customer.family_name) self.assertEqual('spearhead', customer.created_user.username) self.assertEqual('warhead', customer.updated_user.username) Problem: The middleware break it with Exception File "/Users/el/Code/norak-cutter/soken/soken-web/soken_web/middleware.py", line 47, in process_request data['PATCH'] = json.loads(request.body) File "/Users/el/.pyenv/versions/soken/lib/python3.6/site-packages/django/http/request.py", line 264, in body raise RawPostDataException("You cannot access body after reading from request's data stream") django.http.request.RawPostDataException: You cannot access body after reading from request's data stream The problem is data has been read before the RESTful api do the job. Then the program raises an exception. def process_request(self, request): if request.path.startswith('/api/'): data = collections.OrderedDict() data["user"] = request.user.username data["path"] = request.path data["method"] = request.method data["content-type"] = request.content_type if request.method == 'GET': data['GET'] = request.GET elif request.method == 'POST': data['POST'] = request.POST # https://stackoverflow.com/questions/4994789/django-where-are-the-params-stored-on-a-put-delete-request # elif request.method == 'PUT': # data['PUT'] = json.loads(request.body) # test_mobile_update_customer # raise RawPostDataException("You cannot access body after reading from request's data stream") # django.http.request.RawPostDataException: You cannot access body after reading from request's data stream # elif request.method == 'PATCH': # data['PATCH'] = json.loads(request.body) elif request.method == … -
Assigning global variable in django
Here's the view, def notifications(request): new_data = Answer.objects.all() return render(request, 'base.html', {'new_data': new_data}) I've created a popup window for notifications just like stack-overflow has but I can't show the notifications since this view is linked to a URL. So, firstly I need to go to the URL only then click on notification button to make notifications appear. If i don't go to URL, it's just showing a blank window. I tried context_processors.py file in app & added TEMPLATE CONTEXT PROCESSOR in settings.py file but nothing is working. I'm not sure if it's the right way in django 1.11. How can I fix this? -
Django Calling Class Based Mixin from Another Class Based Mixin
My code is having two mixins, BasicAuthMixin and JWTAuthMixin as mentioned below. Just assume that self.authenticate method returns True and doesn't raise any exception: from django.http import JsonResponse from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt from django.views.generic import View class BasicAuthMixin(View): """ Add this mixin to the views where Basic Auth is required. """ @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): try: self.authenticate(request) except: return JsonResponse({'status': 403, 'message': 'Forbidden'}, status=403, content_type='application/json') return super(BasicAuthMixin, self).dispatch(request, *args, **kwargs) class JWTAuthMixin(View): """ Add this mixin to the views where JWT based authentication is required. """ @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): try: self.authenticate(request) except: return JsonResponse({'status': 403, 'message': 'Forbidden'}, status=403, content_type='application/json') return super(JWTAuthMixin, self).dispatch(request, *args, **kwargs) These mixins are being used in the views based upon the authentication needed. The actual problem begins from here: I'm trying to create another mixin AllAuthMixin which when included in any view will automatically determine which mixins need to be called based upon the Authentication Header provided: class AllAuthMixin(View): @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): auth = request.META.get('HTTP_AUTHORIZATION') or '' if auth.startswith('Bearer'): return JWTAuthMixin.as_view()(request, *args, **kwargs) elif auth.startswith('Basic'): return BasicAuthMixin.as_view()(request, *args, **kwargs) raise Exception('Unauthorized Access to Saurav APIs', 403) Once I include AllAuthMixin in any of the … -
Providing download link to user in django
I am uploading files through form and displaying all uploaded file. And now i want to provide link to download any selected file for user, can someone guide me for this ? Thanks in advance -
Connect django with a mssql server using pymssql
I'm trying to connect an apllication on django (v1.11) using pymssql, and I don't know how to make it work. I have followed this steps: > apt-get install freetds-dev (v0.91) > pip install pymssql (v2.1.3) > pip install django-mssql (v1.8) > pip install django-pymssql (v1.7.1) And in settings.py I added: DATABASES = { 'default': { 'ENGINE': 'sqlserver_pymssql', 'HOST': '', 'PORT': '', 'NAME': '', 'USER': '', 'PASSWORD': '', }, } But I have a "TypeError: 'NoneType' object is not callable" error. Is there anything else I should do to configure it? I have tried adding these imports too: import sqlserver_pymssql import sqlserver_pymssql.base but nothing. Any idea? -
FieldError: Unknown field(s) (received_time) specified for Event. Check fields/fieldsets/exclude attributes of class EventAdmin
I have the following model class Event(models.Model): product_type = models.CharField(max_length=250, null=False, blank=False) received_time = models.DateTimeField(editable=False) in admin: class EventAdmin(admin.ModelAdmin): fields = ['product_type', 'received_time'] I get the following error when trying to edit an event (clicking on an individual event in the admin): FieldError at /admin/events/event/20/ Unknown field(s) (received_time) specified for Event. Check fields/fieldsets/exclude attributes of class EventAdmin. I do see that editable=False but I still want it to at least be visible, even it it isn't editable. Is there a way to fix this error and edit these items in admin? Thank you -
Assigning a Global Variable django
Here's my code, def notifications(request): new_data = Answer.objects.all() return render(request, 'base.html', {'new_data': new_data}) I have 2 apps in my project. I wants to use data stored in new_data variable in several templates. I can't extend the template. Is there any other way for doing so? -
imoprt error when I gave source toaster start in morty
I got below error when i run poky/build$ source toaster start. The system will start. Traceback (most recent call last): File "/home/siva/yocto/Morty/poky/bitbake/bin/../lib/toaster/manage.py", line 10, in <module> execute_from_command_line(sys.argv) ...... from .management import update_contenttypes ImportError: cannot import name 'update_contenttypes' I have seen the below link but I believe That is diiferent than this. importerror: cannot import name update _all_content -
Django class view: __init__
Im newcomer to python and django and I need some help with class views. I want to get < Model > value from url, and use it as init parameter in my class. urls.py url(r'^(?P<Model>\w+)/foo/$', views.foo.as_view(), name='foo_class'), views.py class foo(CreateView): def __init__(self, **kwargs): text = kwargs['Model'] #this is not working text = kwargs.get('Model') #nethier this Bar(text) ... Clearly, I'm missing something, or my understanding of Url <> class view is wrong. -
Django/template_block doesn't be operated
Thanks in advance. I have a code below "index.html" <!DOCTYPE html> <html> <head> </head> <body> {% block content %}{% endblock %} </body> </html> and I have another html code("maintab.html") for child of "index.html" {% extends "encyclopeida/index.html" %} {% block content %} <p>Hello world</p> {% endblock %} but it doesn't work.. my contact path is "browser -> "http://localhost/encyclopedia/"(by urls) -> function def("by view.py") -> index.html" and below is my folder structure. enter image description here -
Issue with url returned after login with facebook/google + in an django app
I am building an app using django 1.11 and providing users option to Login with Facebook and Login with Google. For this I am using social-auth-app-django 1.2.0. On successful login, I redirect it to a page – UserProfile.html – setting.py AUTH_PROFILE_MODULE = 'home.UserProfile' where home is an app. urls.py of project (say myProject) url(r'^myProject/',include('home.urls')), url('^complete/facebook/', include('home.urls')), url('^complete/google-oauth2/', include('home.urls')), urls.py in home app url(r'^ UserProfile.html',views. UserProfile,name=' UserProfile ') But the url generated after Login with Facebook is – http://localhost:8000/complete/facebook/UserProfile.html#= which should have been - http://localhost:8000/myProject/UserProfile.html Similar is the issue when user tries Login with Google. URL generated – localhost:8000/complete/google-oauth2/UserProfile.html# which should have been – localhost:8000/myProject/UserProfile.html Please assist and let me if I am missing something. -
Django + nginx + uwsgi how to use one domain to build multiple application?
My question is how can I use one domain (mydomain.com) to build multiple django server? This is my nginx.conf, upstream django_myproject { server unix:///home/frank/myproject/haunyu.sock; # for a file socket } server { listen 80; server_name mydomain.com; # This is my ow charset utf-8; client_max_body_size 75M; # adjust to taste # Django media location /media { alias /home/frank/myproject/media; } location /static { alias /home/frank/myproject/static; } location / { uwsgi_pass django_myproject; include /home/frank/myproject/uwsgi_params; # uwsgi_read_timeout 600; } } I try to let location "/" replace to location "/first_app" like this location /frist_app { uwsgi_pass django_myproject; include /home/frank/myproject/uwsgi_params; # uwsgi_read_timeout 600; } } Then I try to type domain/frist_app to browser, I got 404, My uwsgi also has no contact message. -
Why is Django connection.cursor query failing?
I am getting the following error message when trying to execute a cursor query against a SQLite3 database: My code is as follows: qry = ('select balancer_security.id, balancer_security.name, balancer_security.symbol, ' 'balancer_securityprice.at_dt, balancer_securityprice.price, balancer_securityprice.notes ' 'from balancer_security LEFT OUTER JOIN balancer_securityprice ' 'ON (balancer_security.id = balancer_securityprice.security_id ' 'AND balancer_securityprice.at_dt="?") ' # 'AND balancer_securityprice.at_dt="%s") ' 'ORDER BY balancer_security.name') from django.db import connection cursor = connection.cursor() cursor.execute(qry, [date]) solution = cursor.fetchall() The error occurs on the cursor.execute line. date is a string containing the value 2017-10-05 Also, is the parameter put into the query within django or is it passed to SQLite (i.e. should my parameter placeholder be %s or ?)? Thanks! -
You may need to add 'www.example.com' to ALLOWED_HOSTS (but it is there)
As title shows, I get the You may need to add 'www.example.com' to ALLOWED_HOSTS ... (but it is there) Trying another approach, I simply put ALLOWED_HOSTS = ['*'] which if I am not mistaken allows any host, and should solve the issue for all hosts, but same error is thrown. Is there any other common cause responsible for this that I should check? The only other possible issues I can think of: Domain propagation is still happening since its a new domain (though I can't fathom how it would affect this, since the website is reached) I am using the same app (webfaction) for two sites. Is it favoring one domain over the other? Out of ideas beyond that. Any suggestions? -
Django MPTT Filter Only if No Children Exist
So I am using MPTT for a Category model in Django, and I was wondering if there is a way to filter a Category if there is no child. models.py: class Category(MPTTModel, TimeStampedModel): title = models.CharField(max_length=75) parent = TreeForeignKey('self', null=True, blank=True, on_delete=models.SET_NULL, related_name='children', db_index=True) Categories example in DB: Games > Nintendo > Nintendo 64 Games > Microsoft > Xbox One I want to be able to run a command like this: Category.objects.all().has_no_children() Hoping that it would return [Nintendo 64, Xbox One] -
Django: I have a Profile model, and I want the slug for the profile detail page to be username, which is stored in User model
I'm creating a website where every User has an associated Profile instance, because I want the User model to only handle authentication-related user functions and the Profile model to handle everything else (such as user-uploaded images, etc.) Profile has a User OneToOneField. However, I want to be able to access each profile's detail page using the url pattern site/profile/[username]/. This is impossible without storing the username in both the User and the Profile models, since the slug_field for the Profile DetailView has to be a primary key of Profile, and the username is a field of User. Is there any way to do this without storing the username in two different places? -
possible to group urlpatterns of the same app?django
I know that in each app, we can use our own urlpatterns and include it in the main project / app using include. I am wondering if an app have a few different urls, is there a way to group it? for example urlpatterns = [ url(r'^user/$', hello.asView(), url(r'^user/hello/$', hello.asView(), url(r'^user/there/$', hello.asView(), url(r'^user/here/$', hello.asView(), url(r'^user/that/$', hello.asView(), url(r'^user/mini/$', hello.asView(), url(r'^user/max/$', hello.asView(), url(r'^bb/$', hello.asView(), url(r'^bb/hello/$', hello.asView(), url(r'^bb/there/$', hello.asView(), url(r'^bb/here/$', hello.asView(), url(r'^bb/that/$', hello.asView(), url(r'^bb/mini/$', hello.asView(), url(r'^bb/max/$', hello.asView(), ] please ignore all the hello.asView() but I am wondering if there's a way to group all the user and bb so if there are more url, I don't need to keep on typing user or bb again? thanks in advance for any help. -
Django updating model has broken the admin
I updated my models class called Account. I have removed a field called "user" Removed this line: user = models.ForeignKey(User, unique=True) I then ran makemigration and then migrate successfully. When I goto: http://127.0.0.1:8000/admin/reports/account/ I get the below error message: Account' object has no attribute 'user' My question is, how do I update the admin code easily when making structural changes to my models/migration?