Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to reference the users model using Django-Allauth
I'm looking to use get_object_or_404(MyModel, pk=1) for a allauth user but I don't know how to create the MyModel part. -
NoReverseMatch at account/reset/done in django password reset feature
I am using django(1.10) default password reset feature.I am getting the below error when I change the password from the password reset form. Reverse for 'login' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] Template error: In template C:\pyprojects\cias\ciasproj\ciassite\templates\registration\password_reset_complete.html, error at line 5 Reverse for 'login' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] 1 : {% extends 'base.html' %} 2 : 3 : {% block content %} 4 : <p> 5 : Your password has been set. You may go ahead and <a href=" {% url 'login' %} ">sign in</a> now. 6 : </p> 7 : {% endblock %} register/password_reset_complete.html {% extends 'base.html' %} {% block content %} <p> Your password has been set. You may go ahead and <a href="{% url 'login' %}">sign in</a> now. </p> {% endblock %} accounts/urls.py -- urlpatterns = [ url(r"^signup/$", views.signup, name="account_signup"), #url(r'^login/$', views.login, {'template_name': 'accounts/login.html'}, name='login'), url(r'^login/', views.login_view, name='account_login'), url(r'^logout/$', auth_views.logout, {'next_page': '/account/login'}, name='logout'), url(r'^confirmemail/$', views.confirmemail, name='account_confirmemail'), url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',views.activate, name='activate'), url(r'^activate/',views.activate, name='empty_activate'), url(r'^password_reset/$', auth_views.password_reset, name='password_reset'), url(r'^password_reset/done/$', auth_views.password_reset_done, name='password_reset_done'), url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,23})/$', auth_views.password_reset_confirm, name='password_reset_confirm'), url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', auth_views.password_reset_confirm, name='password_reset_confirm'), url(r'^reset/done/$', auth_views.password_reset_complete, name='password_reset_complete'), ] I tried to modify the html link as {% url reverse('account_login:login') %} But that is … -
Django registration 'AnonymousUser' object has no attribute '_meta'
I have created a website where the user will login with his email instead of username as Django does. So, I have created an AUTHENTIFICATION_BACKENDS: class EmailBackend(object): def authenticate(self, username=None, password=None, **kwargs): try: user = User.objects.get(email=username) except User.MultipleObjectsReturned: user = User.objects.filter(email=username).order_by('id').first() except User.DoesNotExist: return None if getattr(user, 'is_active') and user.check_password(password): return user return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None My form: class UserRegisterForm(forms.ModelForm): username = forms.CharField() email = forms.EmailField() age = forms.IntegerField() password2 = forms.CharField() password = forms.CharField() class Meta: model = User fields = ['username', 'age', 'email', 'password', 'password2'] At this stage, the login with an email is Working perfectly. The problem starts when I try to register a user. In registration view: form = UserRegisterForm(request.POST) register a new user: user = form.save(commit=False) username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() user = authenticate(username=username, password=password) login(request, user) This is where the problem appears. it seems like user = authenticate(username=username, password=password) is trying to create an anonymous user. What am I doing wrong in my AUTHENTIFICATION_BACKENDS ?? -
Add E-Mail header in django
So I have a code like this in the views.py from django.core.mail import send_mail send_mail( 'subject', 'message.', 'info@xyz1234.de', ['test1234@gmail.com'], fail_silently=False, # headers={'List-Unsubscribe': '<http://www.xyz1234.de/unsubscribe123'}, ) I want to add the header 'List-Unsubscribe' but it doesn't work and I get a server error. If I use the code with '#' the code works fine. How can I add this header? Thanks. -
Wagtail - display the three latest posts only on the homepage
I have created a model to show posts on the homepage, but only want the three latest posts to show. Do I need to use pagination for this, or is there a hook I can use instead? I was thinking I could use pagination and just not include the 'next' button, but that seems somewhat like a hack, and I want to do this the right way. I am still very new to Django and Python and am going to continue experimenting, but if someone could point me in the right direction I would be very grateful. Here's the HomePage model: from __future__ import unicode_literals from django.db import models from wagtail.wagtailcore.models import Page from wagtail.wagtailcore.fields import RichTextField from wagtail.wagtailadmin.edit_handlers import FieldPanel from blog.models import BlogPage class HomePage(Page): def blogs(self): blogs = BlogPage.objects.all() blogs = blogs.order_by('-date') return blogs Here's the BlogPage model: class BlogPage(Page): body = RichTextField(verbose_name=_('body'), blank=True) tags = ClusterTaggableManager(through=BlogPageTag, blank=True) date = models.DateField( _("Post date"), default=datetime.datetime.today, help_text=_("This date may be displayed on the blog post. It is not " "used to schedule posts to go live at a later date.") ) header_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+', verbose_name=_('Header image') ) author = models.ForeignKey( settings.AUTH_USER_MODEL, blank=True, null=True, limit_choices_to=limit_author_choices, … -
PUT and GET single element not working at DJANGO using rest-api. (BUT POST & GET WORKS!)
I'm trying to work with django & rest api. The get & post functions are working for me, (for example at /users/ but i'm trying to access a specific user (for example /users/1 - for the user with id 1 - primary key) And i'm receiving this error: TypeError at /users/1 put() missing 1 required positional argument: 'pk' I think it has something to do with the urls. Hi friends! I'm trying to work with django & rest api. The get & post functions are working for me, (for example at /users/ but i'm trying to access a specific user (for example /users/1 - for the user with id 1 - primary key) And i'm receiving this error: TypeError at /users/1 put() missing 1 required positional argument: 'pk' I think it has something to do with the urls. Hi friends! I'm trying to work with django & rest api. The get & post functions are working for me, (for example at /users/ but i'm trying to access a specific user (for example /users/1 - for the user with id 1 - primary key) And i'm receiving this error: TypeError at /users/1 put() missing 1 required positional argument: 'pk' I think … -
unable to acces admin panel in django
i am creating a todo application using django, but while redirecting to http://127.0.0.1:8000/admin/ i get error 'module' object has no attribute 'getitem' Request Method: GET Request URL: http://127.0.0.1:8000/admin/login/?next=/admin/ Django Version: 1.11.2 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', 'todolist.apps.TodolistConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Exception Type: TypeError at /admin/login/ Exception Value: 'module' object has no attribute '__getitem__' -
Django Automatically call method after data is added DB
After adding data to a certain table in DB through Django admin I want a method to be called automatically to process this data (before or after it was added to DB) and save the output in a different table, so that when user logs in the view doesn't have to wait for processing of that data and only query a table for prepared output. -
Twitter.error.TwitterError: {'message': '"user_id" must be type int'}
I am trying to "python-twitter" in my django project. My code tweet = cache.get('tweet') if not tweet: tweet = twitter.Api().GetUserTimeline( settings.TWITTER_USER )[0] tweet.date = datetime.strptime( tweet.created_at, "%a %b %d %H:%M:%S +0000 %Y" ) cache.set( 'tweet', tweet, settings.TWITTER_TIMEOUT ) But I am getting below error Twitter.error.TwitterError: {'message': '"user_id" must be type int'} I have set the variables to TWITTER_USER = 'CaseyNeistat' TWITTER_TIMEOUT = 3600 as the blog suggested then why the error. Is there anything I am doing wrong? -
Partial object returned when Serializing a model with relationship
So I have two models Foo and Bar. Foo has a one to many relationship with Bar as shown below. app/models.py class Foo(models.Model): id = models.IntegerField(primary_key=True) sourceid = models.IntegerField(blank=True, null=True) name = models.TextField(unique=True, null=True) url = models.TextField(unique=True, null=True) created_at = models.DateTimeField(default=datetime.datetime.utcnow, null=True) updated_at = models.DateTimeField(default=datetime.datetime.utcnow,null=True) class Meta: managed = False db_table = 'foo' class JSONAPIMeta: resource_name = 'foo' class Bar(models.Model): id = models.IntegerField(primary_key=True) parent_foo = models.ForeignKey(Foo, models.DO_NOTHING, db_column='parentId') # Field name made lowercase. url = models.TextField() extension = models.ForeignKey('self', models.DO_NOTHING, db_column='extensionId', blank=True, null=True) created_at = models.DateTimeField(blank=True, null=True) updated_at = models.DateTimeField(blank=True, null=True) class Meta: managed = False db_table = 'bar' Now the issue is that I want to create a serializer FooBarList that nests Bars into Foo. I have managed to slightly achieve this with the following code: app/serializers.py class FooBarList(serializers.ModelSerializer): class Meta: model = Foo fields = ('id','name','url','created_at','updated_at','bar_set') When I call this serialise function the issue arrises... Only the 'id' parameter of the Bar object is shown in the response. This is shown below: JSON Output { "data": [ { "attributes": { "created_at": "2017-08-23T16:07:11.384209Z", "name": "TestFoo", "updated_at": "2017-08-23T17:41:17.179040Z", "url": "TestFoo.org" }, "id": "1", "relationships": { "Bar": { "data": [ { "id": "1", "type": "Bar" }, { "id": "2", "type": "Bar" … -
Where is account login template under mezzanine?
I'm trying to look for the login page. I've created a folder registeration/login.html under templates, but it doesn't read my updated file at all. Secondly, there's a button that says login but takes me to accounts/login page, how do I just forward the url to accounts/login then? and where do i customize the login page? I've tried creating an accounts/loginunder templates, that doesn't work. urls.py url('^', include('django.contrib.auth.urls')), -
How to make Django-Oscar appear as a separate app in Django admin panel?
Good day y'all! Here comes a basic Django question: I was running a Django project with one app in it and installed Django-Oscar to cover my ecommerce needs. So, I pip installed it in my main project and set everything up the way they explain it on readthedocs. Now, the structure of my admin panel looks like this: Main project My app Oscar Address Oscar Analytics Oscar ... And I'd like it to be: Main project My app Shop Oscar Address Oscar Analytics Oscar ... I already did django-admin startapp shop for that matter. Apparently the question is so obvious that I can't find any tutorials for dummies to do this. Can someone point me in the right direction? Maybe a generic tutorial about including apps in apps the right way is laying around somewhere? Thank you in advance. -
How to remove the ?q= from the url in Django
My current url looks like this: [domain name]/?q=[search_term] and would like to make it look like this: [domain name]/[search_term] In my urls.py I have the following code: urlpatterns = patterns('', url(r'^$', 'home', name='home'), url(r'^q=(?P<search_term>[A-Za-z0-9\-]+)$', 'home', name='query'), In views.py the code looks like this: def home(request, search_term='q'): do stuff return render(request, 'template', {context}) For some reason, no matter if I have a search_term in the url or not, the app always serves the first route. What am I doing wrong? -
Django Rest Framework User and UserRole and Permission Handling using Token Authentication
I am newbie to Django Rest Framework. I googled a lot and stuck on How to set User Role to User and strict to Permission. My question is very basic but I don't know how to do it. I want to create 2 types of Users: 1) Admin (Full Access) 2) Normal User (Limited Access) I found some links but still on getting what to do: Django rest-framework per action permission django-rest-framework : setting per user permissions -
How to perform inner join in django
Taking the sentence: select * from auth_permission left join auth_group_permissions on (auth_group_permissions.permission_id = auth_permission.id) How can i do in django with queryset i do not understand how the inner join works in querysets in models of default django auth -
Django social-auth facebook page not found on production
I have ran python-social-auth, on local host connecting to facebook (login). It worked well. But when i push for production and configured the facebook app to take the domain name, site url of my website I ran into page not found error !!! accounts/urls.py urlpatterns = [ # sign url(r'^login/', account_login, name='login'), url(r'^logout/', account_logout, name='logout'), url(r'^signup/', account_register, name='signup'), # social url(r'^social/', include('social_django.urls', namespace='social')), ] -
Weather API django web Scarping
I would like integrate in my Django app the weather condition, so I include the API of a weather service. The problem is this: I would like to show only the icons which show the daily weather's condition. So I'm interesting only to this data!! To do this I have thought to use web scarping procedure... Is this the better way? Sorry for my bad English -
How to run tests with `DEBUG=TRUE` in Django
I am trying to write tests for my custom Error Page view:- Docs can be found here Also for writing test cases for i have included these urls as suggested here :- if settings.DEBUG: urlpatterns += [ url(r'^404/$', page_not_found_view), url(r'^500/$', my_custom_error_view), url(r'^400/$', bad_request_view), url(r'^403/$', permission_denied_view), ] handler404 = page_not_found_view handler500 = my_custom_error_view handler403 = permission_denied_view handler400 = bad_request_view and views.py is :- def page_not_found_view(request): t = loader.get_template('error/HTTP404.html') html = html = t.render({}) return HttpResponseNotFound(html) def my_custom_error_view(request): t = loader.get_template('error/HTTP500.html') html = html = t.render({}) return HttpResponseServerError(html) def permission_denied_view(request): t = loader.get_template('error/HTTP403.html') html = html = t.render({}) return HttpResponseForbidden(html) def bad_request_view(request): t = loader.get_template('error/HTTP400.html') html = html = t.render({}) return HttpResponseBadRequest(html) When i am hitting that urls manually i am getting proper response code i.e 500 for visiting /500 and so on. Since those urls will be included only if setting.DEBUG=True by default and the test cases run in DEFAULT=False and mode i tried to override it using @override_settings decorator My test.py file is :- @override_settings(DEBUG=True) class ErroCodeUrl(TestCase): def test_400_error(self): response = self.client.get('/400/') self.assertEqual(response.status_code, 500) def test_403_error(self): response = self.client.get('/403/') self.assertEqual(response.status_code, 500) def test_404_error(self): response = self.client.get('/404/') self.assertEqual(response.status_code, 500) def test_500_error(self): response = self.client.get('/500/') self.assertEqual(response.status_code, 500) But using this @override_settings is … -
Bootstrap 3.3.7 Grid system column large dose not work
Bootstrap 3.3.7 Column large not working as expected. but the weird part is. when i try to use bootstrap 4. it works perfectly. i don't know where the problem comes from. besides that. bootstrap 4 changes the sizes of my text. and i don't feel like upgrading. My bootstrap is linked in my app perfectly. no issues there. i need help in why bootstrap 3.3.7 column large isn't working. here is my code base.html <html> {% load static %} <link rel="stylesheet" href=" {% static 'assets/css/main.css' %} " /> <link rel="stylesheet" href=" {% static 'assets/bootstrap/css/bootstrap.css' %} "> <link rel="stylesheet" href=" {% static 'assets/bootstrap/css/bootstrap.min.css' %} "> <link rel="stylesheet" type="text/css" href=" {% static 'assets/css/responsive.css' %} "> <script src=" {% static 'assets/js/jquery.js' %} "></script> <script src=" {% static 'assets/js/script.js' %} "></script> {% block content %} {% endblock content %} <div id="footer" class="container-fluid"> <div class="row"> <div class="col-lg-3 col-md-3 col-sm-3 col-xs-12"> <h3> Get to know us </h3> <div> <label> Work with US </label> <label> Work with US</label> <label> Work with US </label> </div> </div> <div class="col-lg-3 col-md-3 col-sm-3 col-xs-12"> <h3> Learn with US </h3> <div> <label>Work with US </label> <label> Work with US </label> </div> </div> <div class="col-lg-3 col-md-3 col-sm-3 col-xs-12"> <h3> Work with US </h3> … -
How to design Oauth 2.0 django authentication server with login and signup pages
I have developed an authentication system in django python 0Auth2. Which provide some endpoint for user authentication. Some are front end application(Angular) which are using this authentication system. Now i want to create login and sign up pages in oauth server so every angular application will use this for user interaction i.e. asking user name and password to user. My question is that how i can create this pages in Oauth server and how to use this created pages in other angular application. -
is it possible to do a query inside a tasks.py with celery
totally new to celery and wondering if you can run a query on a table inside a celery task? celery is working and i can queue jobs, however, i tried this and it gives an error: import celery from celery import shared_task from django.shortcuts import get_object_or_404 from frontendapp.models import xlinkdatabase @shared_task def lookup(lookup_id): look_up_result = get_object_or_404(xlinkdatabase,MEMBER_ID=lookup_id) return look_up_result error: kombu.exceptions.EncodeError: Object of type 'xlinkdatabase' is not JSON serializable what am I doing wrong? -
Django/Jinja - passing variable to button from textarea
I would like to pass whatever the user input in the text area to the button to open a new page as shown in the graph. How should I create (set?) the variable "{{ analysis_id }}"? Thank you! Please check the image here Text area: <div class="field"> <label for="geneid">Input sequence (Amino acid or Nucleotide) or Gene ID </label> <textarea name="geneid" id="geneid" rows="6"></textarea> </div> The button: <button onclick="location.href='/analysis/{{ analysis_id }}';" type="submit" class="btn btn-success">Submit</button> -
In Django/Python how to handle exception - list index out of range for empty table?
My problem is that when my Database is empty I am getting this error IndexError at / list index out of range > period = Period.objects.all() > try: > period_current = [obj for obj in period if ((obj.is_current)==True)] > total_payment_period_current_dict = LeasePayment.objects.filter(payment_date__range=[period_current[0].start_date, > period_current[0].end_date]).aggregate(Sum('amount')) ... > total_payment_period_current = total_payment_period_current_dict['amount__sum'] > except ValueError: > raise Http404("Can't perform calculation for total_payment_period_current, check data ") I hoped I can handle it with exeption to give meaningful error , but it doesn't work. What I can do to give meaningful error . Or ideally to avoid this exception all together in case of empty tables? -
Error while deloying Django application with Gunicorn?
I tried to deploy a django app using ngnix-gunicorn like here: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04 I did it without virtualenv. Here is the 'gunicorn.service' file. When I tried to make a systemd, I facing an error. [Unit] Description=gunicorn daemon After=network.target [Service] Environment=SECRET_KEY='*uj$' User=root Group=www-data WorkingDirectory=/root/myproject ExecStart=/usr/local/bin/gunicorn --access-logfile - --workers 3 --bind unix:/r$ [Install] WantedBy=multi-user.target Here is here is the error while creating a systemd. ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Sat 2017-08-26 14:05:19 UTC; 6s ago Process: 24747 ExecStart=/usr/local/bin/gunicorn --access-logfile - --workers 3 --bind unix:/root/test1/test1.sock test1.wsgi:applica Main PID: 24747 (code=exited, status=200/CHDIR) Aug 26 14:05:19 ip-172-31-1-229 systemd[1]: Started gunicorn daemon. Aug 26 14:05:19 ip-172-31-1-229 systemd[1]: gunicorn.service: Main process exited, code=exited, status=200/CHDIR Aug 26 14:05:19 ip-172-31-1-229 systemd[1]: gunicorn.service: Unit entered failed state. Aug 26 14:05:19 ip-172-31-1-229 systemd[1]: gunicorn.service: Failed with result 'exit-code'. Thanks in advance . -
How do I store python code in my database for a project running Django?
Basically, I want to store python modules with a few simple functions in my database. My project runs on Django. I came across python_field, however, its buggy. I want to execute the code on the save method for the Model. What is the standard way to do this? Thanks.