Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ForeignKey object has no attribute model?
I am running the code below and get back an error saying 'ForengKey object has no attribute model'. What is wrong with this? I thought it only takes one argument, the foreignkey model? from django.db import models from incentives.models import Incentive slug = models.CharField(max_length=150) incentive = models.ForeignKey(Incentive) print(incentive) '''incentive = models.ForeignKey( Incentive, on_delete=models.CASCADE, verbose_name=__('')) -
Registration using e-mail, Django 2.0
I'm just a beginner, so i got some questions making my first project. I've got code in views: def signup(request): if request.method == 'POST': form = SignupForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) mail_subject = 'Активация' message = render_to_string('acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':account_activation_token.make_token(user), }) print(message) # здесь я смотрю какое сообщение отправляю to_email = form.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return HttpResponse('Пожалуйста, подтвердите адрес электронной почты') else: form = SignupForm() return render(request, 'signup.html', {'form': form}) def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) # return redirect('home') return HttpResponse('Thank you for your email confirmation. Now you can login your account.') else: return HttpResponse('Activation link is invalid!') This code is from urls: from . import views from django.urls import path urlpatterns = [ path('', views.signup, name='signup'), path('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'), ] The problem is that i always get invalid URL in my email. I think it is about new 'path' function, which may be used is <int:uidb64> but not really sure. Thank for your help! -
The custom page 404 is not showing but the page 500 is showing
When I load an inexistent url the page 404 does not show instead the page 500 is shown. Below my setups. Could you please guide me to turn Django on to show 404 page? Thanks Ubuntu Server 16.04 ; Python 3.5.2 ; Django 2.0 cat contatoproj/urls.py from django.contrib import admin from django.urls import path from django.conf.urls import url from django.conf.urls import include from django.conf.urls import handler404, handler500 from contatoapp import views from contatoapp import views as myapp_views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.index, name='index'), url(r'^contato', views.contato, name='contato'), ] handler404 = myapp_views.error_404 handler500 = myapp_views.error_500 cat contatoapp/views.py from django.shortcuts import render from django.http import HttpResponse from django.template import RequestContext from django.contrib import messages from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse, HttpResponseRedirect from django.conf import settings from contatoapp.forms import ContatoForm def error_404(request): data = {} return render(request, 'ops404.html', data) def error_500(request): data = {} return render(request, 'ops500.html', data) $ ls -la templates/ops* -rwxr-xr-x 1 admweb admweb 614 Dec 13 15:31 templates/ops404.html -rwxr-xr-x 1 admweb admweb 614 Dec 13 15:29 templates/ops500.html cat contatoproj/settings.py DEBUG = False ALLOWED_HOSTS = ['*'] -
Authentication with django-rest-framework-social-oauth2
I apologize in advance for my English, i try use django-rest-framework-social-oauth2 for api Authentication. I followed the steps in this tutorial https://github.com/PhilipGarnero/django-rest-framework-social-oauth2 if go to http://127.0.0.1:8000/auth/login/facebook/ after that djangoadmin does not ask login and password, but if go to other my api route, then i get an error saying "detail": "Authentication credentials were not provided." my settings REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', 'rest_framework_social_oauth2.authentication.SocialAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ] } TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', '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', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] thanks in advance -
reach object detail in template using Listview class django 2
im following a totorial and im tying to show each object peroperty (that are saved in db) in my template html file like this {% for obj in objects_list %} <p>{{ obj.name }} => {{ obj.location }} <b>timecreated</b>==> {{ obj.timestamp }} <b>time updated</b>==> {{ obj.updated }}</p> {% endfor %} i should get slug in url and this url http://localhost:8000/restaurants/shomal/ /shomal/ is our slug and we must watch object detail where category is equl to = shomal but i cant see for loop result in template but when in print queryset i can see object detail in terminal why cant i reach object detail in template for loop in my app view file i have from django.shortcuts import render from django.shortcuts import HttpResponse from django.views import View from django.views.generic import TemplateView, ListView from .models import Restaurant from django.db.models import Q def restaurants_listview(request,): template_name = 'restaurants/restaurants_list.html' query_set = Restaurant.objects.all() context = { "objects_list": query_set } return render(request, template_name, context) class RestaurantListView(ListView): template_name = 'restaurants/restaurants_list.html' def get_queryset(self): print(self.kwargs) slug = self.kwargs.get("slug") if slug: queryset = Restaurant.objects.filter( Q(category__iexact=slug)| Q(category__icontains=slug) ) print(queryset) # return queryset else: queryset = Restaurant.objects.all() return queryset and in django url.py file i have from django.contrib import admin from django.urls import … -
Querying Binary data using Django and PostgreSQL
I am trying to print out to the console the actual content value (which is html) of the field 'htmlfile': 16543. (See below) So far I am able to print out the whole row using .values() method Here is what I am getting in my python shell: >>> >>> Htmlfiles.objects.values()[0] {'id': 1, 'name': 'error.html', 'htmlfile': 16543} >>> I want to print out the content of 16543.. I have scanned through the Django QuerySet docs so many times and still cannot find the right method.. Any assistance would be greatly appreciated. -
When I attempt to insert data to my connected database it shows another database and raises an error
In Django, when I attempt to insert data to my connected database it shows another database and raises an error. I connect to database 'test'. Then I create tables using Python. Then I drop all tables in Navicat. Then I change connection to database 'books'. Then I do the same action. I get this error: OperationalError: (1049, "Unknown database 'test'") My settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'books', 'USER':'root', 'PASSWORD':'1234', 'HOST':'localhost', 'PORT':'3306' } } from books.models import Publisher p1 = Publisher(name='Apress', address='2855 Telegraph Avenue', ... city='Berkeley', state_province='CA', country='U.S.A.', ... website='http://www.apress.com/') p1.save() -
Getting a validation error on filtering inlines on Django Admin
There are an Invoice model and two Pricing models to calculate billing amount. I want detail pages of Invoice item on Django admin to show the only one inline determined by the attribute of Invoice model (pricing_type). To achieve above, I wrote the code below but it raised an error(django.core.exceptions.ValidationError: ['ManagementForm data is missing or has been tampered with']) when I saved Invoice item on Django admin with the modified pricing_type. How can I make inlines on detail pages switchable? class PricingAInline(admin.TabularInline): model = PricingA class PricingBInline(admin.TabularInline): model = PricingB @admin.register(Invoice) class InvoiceAdmin(admin.ModelAdmin): inlines = [PricingAInline, PricingBInline] def get_formsets_with_inlines(self, request, obj=None): if isinstance(inline, PricingAInline) and obj.pricing_type.name == 'basic': yield inline.get_formset(request, obj), inline elif isinstance(inline, PricingBInline) and obj.pricing_type.name == 'advanced': yield inline.get_formset(request, obj), inline continue -
How to connect your social media account to your profile in django-allauth?
I let the registration on the site via email and password. When i login I want to connect to my creating django profile, my social account in facebook. Can someone faced with this? -
I would like to add condition to Django DetailView
I am using Django Generic view, DetailView. But I'd like to block users to access to detail post who did not email_confirmed yet. I have a email_confirmed field in User model. My code is : @method_decorator(login_required(login_url='/login/'), name='dispatch') class RecruitView(generic.DetailView): model = Recruit template_name = 'recruit.html' and I want to add : if not request.user.email_confirmed: error_message = "you did not confirmed yet. please check your email." return render(request, 'info.html', {'error_message': error_message}) else: pass How can I add this condition to DetailView? (I tried to override 'as_view' but I don't know how to do it) -
regular expression error in DJango trying to find index numbers on blog.html
I have the following error while trying to load up specific index numbers (relating to blog posts) using Django. The erroneous code is below - can anyone help point out the error? path(r'(?P)<pk>\d+)', DetailView.as_view(model = Post,template_name = 'blog/post.html')) The whole code on that urls.py file to show context is here: from django.urls import path from django.conf.urls import url, include from django.views.generic import ListView, DetailView from blog.models import Post #it's already going to blog/, so this regular expression is just blank urlpatterns = [ path(r'', ListView.as_view(queryset=Post.objects.all().order_by("-date") [:25], template_name="blog/blog.html")), path(r'(?P)<pk>\d+)', DetailView.as_view(model = Post,template_name = 'blog/post.html')) ] The URL I am trying to reach is: http://127.0.0.1:8000/blog/2 and the error on page is: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/blog/2 Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ [name='index'] blog/ blog/ (?P)<pk>\d+) The current path, blog/2, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. Succinctly, I need help in finding the error in the following code snippet (the first path works fine, it is the SECOND PATH that doesn't) urlpatterns … -
how to print model data in django. i should be able to print the field inputs in te next page after clicking submit button
models.py i have created a Model i.e Form_db,now i want to print that information using template thanks.html from django.db import models from django import forms # Create your models here. class Form_db(models.Model): name = models.CharField(max_length=50) email = models.EmailField(max_length=50) number = models.CharField(max_length=15) any_query = models.TextField(blank=True,max_length=100) address = models.TextField(max_length=100,blank=True) def __str__(self): # __unicode__ on Python 2 return self.name forms.py from django import forms from .models import Form_db class Form_db_att(forms.ModelForm): class Meta: model = Form_db fields= ['name','email','address','number','any_query'] views.py from django.http import HttpResponseRedirect, HttpResponse, request from django.shortcuts import redirect ,render from .forms import Form_db_att from django.utils import timezone from .models import Form_db # Create your views here. def home(request): if request.method == 'POST': form = Form_db_att(request.POST) if form.is_valid(): model_instance = form.save(commit=False) model_instance.timestamp = timezone.now() model_instance.save() return HttpResponseRedirect('/home/test') else: form = Form_db_att() return render (request,'mforma/name.html',{'form':form}) def thanks(request): form = Form_db(request.POST) return render(request,'mforma/thanks.html',{'form':form}) thanks.html form.id is returning values with csrf token and presenting the field values in list format. <form action="" method="post"> {{form.id}} </form> name.html <form action="/home/thanks/" method="post" > {% csrf_token %} {{form.as_p}} <input type="submit" value="submit"> </form> mformp/urls.py from django.contrib import admin from django.conf.urls import url , include urlpatterns = [ url('admin/', admin.site.urls), url('home/',include('mforma.urls')), ] mformp/urls.py from django.conf.urls import url from . import views urlpatterns =[ … -
how to develop two django apps using the same template and reuse them in some other projects?
Here is the scenario: Mysite: a normal website without any login feature, and using App1 to provide a login feature. App1: the login app providing twitter auth, and including a login.html template (having a twitter login button) to keep this whole app and Mysite isolated, make it plug and play. Now Mysite needs another 3rd-party login app, App2 to provide facebook auth. The original template login.html is expected to add another login button for facebook. Question is: How to organize the structure, let these two apps using the same template login.html. Then distribute them, so that Mysite could reuse them by pip install. -
Django ORM, data that does not match the condition even though filtering is acquired
There is a model called Anayltics like the following. The url field of this model contains various values (e.g '/login', '/sports/1234', '/search'). class Analytics(models.Model) url = models.CharField(max_length=255, null=True) value = models.IntegerField(null=True) I attempted to retrieve only records with url containing strings in category_list below. category_list = ['fashion', 'food', 'sports'] filter_q = reduce(operator.or_, (Q(url_contains=c) for c in category_url_list)) query = Analytics.objects.filter(filter_q) However, records with unexpected urls, such as url '/login', are also retrieved. Please tell me where is wrong. -
django_filter make filter for a dynamic model
i am using django_filter and i am trying to make a filter out of that model.... but it's dynamic...for example in the filter class..i have to create a meta class and give the model... but i don't have the model (table name) cause it's dynamic... How can i do it? i have here 2 models...1 dynamic and the other 1 not.. models.py def create_pg(db_table): """ :param db_table: :return: """ class CustomMetaClass(ModelBase): def __new__(cls, name, bases, attrs): model = super(CustomMetaClass, cls).__new__(cls, name, bases, attrs) model._meta.db_table = db_table return model class Pages(models.Model): __metaclass__ = CustomMetaClass links = models.CharField(db_column='Links', unique=True, max_length=250) responsetime = models.CharField(db_column='ResponseTime', max_length=50) ceated_at = models.DateTimeField(db_column='Ceated_at') return Pages class Domains(models.Model): website = models.CharField(db_column='Website', unique=True, max_length=250) domain = models.CharField(db_column='Domain', unique=True, max_length=100) tablename = models.CharField(db_column='TableName', unique=True, max_length=100) status = models.IntegerField(db_column='Status') created_at = models.DateTimeField(db_column='Created_at') class Meta: managed = False db_table = 'Domains' def __str__(self): return self.tablename def __unicode__(self): return '%r' % {'tablename': self.tablename} So as you can see my first model is dynamic...my second is not.. The way i am creating the model name is using the tablename from the domains model and i call it.. Example of mysql tables that are for the dynamic model: Page_ExampleCom Page_TestCom Page_DynamicCom etc.. this is my filters.py … -
How to display all the images in a folder by using django
I have a folder which is being populated by images all the time . And I don't know how to make a kind of "loop" which will display all the images in a browser using Django -
Best way to deploy Django on Azure
I'm not sure what the best way would be to deploy Django to Azure. I have done the following: Created a web app container and linked it to my Django bootstrap docker image. This works fine, but my only concern is the DB part. Everytime you rebuild the container, you also rebuilt the DB (SQLite). I thought maybe I should connect to a remote DB via Postgres? As a second option, I have created a virtual server and just created a docker image on there with my Django setup.This is the normal way I setup all my apps in the past, and makes it easier to manage and debug. I get the feeling that the container, although very cool, is more aimed at static kind of apps. But with my kind of app there are constant updates et. Not sure what path to foloow here!? -
How to update multiple records at once (bulk update) in django API
I need to update categories in many Article in one request. In ArticleViewSet I have: def get_serializer_class(self): if self.action in ['partial_update', 'update']: return ArticlePostSerializer return ArticleSerializer So ArticlePostSerializer need to be changed. This is my serializers code: class ArticleShortCategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = 'id', 'name' class ArticleSerializer(serializers.ModelSerializer): categories = serializers.SerializerMethodField() def get_categories(self, obj): return ArticleShortCategorySerializer(obj.categories, many=True).data class Meta: model = Article read_only_fields = 'id' fields = ('categories', 'text') + read_only_fields class ArticlePostSerializer(serializers.ModelSerializer): class Meta: model = Article fields = 'id', 'categories', 'text' I tried to add: class ArticlePostListSerializer(serializers.ListSerializer): and class Meta: list_serializer_class = ArticlePostListSerializer But it doen't work. How to change this code to do multiple update. My json request { [id: 90, categories: [10,12,14]], [id: 93, categories: [10,12,14]], [id: 95, categories: [10,12,14]] } -
Logged in, but cannot retrieve user from request object django
I am trying to access my user object in the django request object in a Class Base View. However, i get the error: module 'django.http.request' has no attribute 'user' Below is my code: class FinanceHomePage(TemplateView): template_name = 'finance/finance_homepage.html' def get_context_data(self, **kwargs): context = super(FinanceHomePage, self).get_context_data(**kwargs) context['username'] = self.request.user.username return context The above code snippet will be reached only after logging in. ** EDIT ** Below is the login view: def user_login(request): if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: if user.is_active: login(request, user) return HttpResponseRedirect(reverse('homepage')) # main page if login is successful else: return HttpResponse("ACCOUNT NOT ACTIVE") else: print('Someone tried to log in and failed') print('Username: {}, password, {}'.format(username, password)) return HttpResponse('Invalid login details supplied') else: return render(request, 'authentication/login.html', {}) Below is the directory of my self.request: ['COOKIES', 'FILES', 'GET', 'META', 'POST', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_cached_user', '_encoding', '_get_post', '_get_raw_host', '_get_scheme', '_initialize_handlers', '_load_post_and_files', '_mark_post_parse_error', '_messages', '_post_parse_error', '_read_started', '_set_post', '_stream', '_upload_handlers', 'body', 'build_absolute_uri', 'close', 'content_params', 'content_type', 'csrf_processing_done', 'encoding', 'environ', 'get_full_path', 'get_host', 'get_port', 'get_raw_uri', 'get_signed_cookie', 'is_ajax', 'is_secure', 'method', 'parse_file_upload', 'path', 'path_info', … -
Django widget with filtering functionality
I have three very simple models: class Tag(models.Model): name = models.CharField(max_length=200) class Task(models.Model): name = models.CharField(max_length=200) tag = models.ManyToManyField(Tag) class Session(models.Model): task = models.ForeignKey(Task) Are there any widgets on GitHub for my task field on Session form, so I can select task with the help on filtration by tag? For example, two select boxes for this one filed. In the first select box I can select the tag, and in the second select I immidiately have reduced set of tasks which have this tag. Sorry for my English. I spent some hours and did not find any widgets with similar functionality. For exapmle "chained selects" - this widget requires addition filelds in the same model... -
Not getting output with cycle tag in django
I am trying my hand on cycle tag of django, but when i use the below code the output is not as expected ``` <style> .row1{ color:blue; } .row2 { color:green; } </style> </head> <body> <h1> this is a world</h1> <p> which is {{ html_temp }}</p> <p> {% for o in list %} <tr class="{% cycle 'row1' 'row2' %}"> {{ o }}</br> </tr> {% endfor %} </p> </body> ``` I got the output as black text instead of colored text because I make the classes row1 and row2 as blue and green respectively. where I am getting it wrong? -
Query for distinct model instances using values from a many to one table in Django ORM
I have three models, called Order, Adjustment, and Location, respectively. My Order model (truncated to only show relevant fields) looks like this: class Order(models.Model): id = models.CharField(max_length=48, primary_key=True) status = models.IntegerField(null=True, default=None) amount = models.FloatField(null=True, default=None) while the Adjustment model looks like this: class Adjustment(models.Model): id = models.CharField(max_length=48, primary_key=True) order = models.ForeignKey(Order, related_name='adjustments', null=True, default=None) type = models.CharField(max_length=50, null=True, default=None) amount = models.FloatField(null=True, default=None) location = models.ForeignKey(Location, null=True, blank=True, default=None) and finally the Location model looks like this: class Location(models.Model): city = models.CharField(max_length=255, null=True, default=None) state = models.CharField(max_length=60, null=True, default=None) state_long = models.CharField(max_length=200, null=True, default=None) county = models.CharField(max_length=60, null=True, default=None) country = models.CharField(max_length=60, null=True, default=None) country_long = models.CharField(max_length=200, null=True, default=None) zipcode = models.CharField(max_length=32, null=True, default=None) longitude = models.FloatField(max_length=10, null=True, default=None) latitude = models.FloatField(max_length=10, null=True, default=None) timezone = models.CharField(max_length=60, null=True, default=None) The code for the query in question lies here: orders = Order.objects.filter( adjustments__type='payment', adjustments__location__isnull=False, status__gte=200, status__lt=300 ) \ .exclude( adjustments__location__zipcode__in=['', '0000', '00000', 0000, 00000] ) \ .values( # 'id', 'adjustments__location__city', 'adjustments__location__state', 'adjustments__location__country' ) \ .annotate( bookings=Count('amount'), #, distinct=True), total_booking_value=Sum('amount'), average_booking_value=Avg('amount') ) Problem Statement: Get all distinct orders where the city, state, and country match and count the number of orders (bookings), their value, and their average value. Currently, there are … -
Django template csv writer inserts blank lines
I am printing some csv file by writing into header_template.csv: {% load devicetags %} {% get_headers device_list %} Now, Django adds a blank line before and after the output of get_headers, which is a comma separated string. The output looks like this: *blank line* a,b,c *blank line* I know that this behaviour often occurs with python, and that normally, I would just have to open the file with 'wb', but I am not directly opening the file here and thus cannot pass a flag. Can I somehow tell Django to use 'wb' instead of 'w'? -
what is dispatch used for in django?
I have been trying to wrap my head around the dispatch method, particularly in Django (please see code example below). However, I cannot seem to figure out exactly what it does. I tried to gain an understanding from the Django docs but didn't find them to informative on this topic. Per my understanding it is a listener that listens to all events happening on a page but I am not sure if this is the case? Thanks. class OrderDetail(DetailView): model = Order def **dispatch**(self, request, *args, **kwargs): try: user_check_id = self.request.session.get("user_checkout_id") user_checkout = UserCheckout.objects.get(id=user_check_id) except UserCheckout.DoesNotExist: user_checkout = UserCheckout.objects.get(user=request.user) except: user_checkout = None obj = self.get_object() if obj.user == user_checkout and user_checkout is not None: return super(OrderDetail, self).dispatch(request, *args, **kwargs) else: raise Http404 -
CSS - float: right moves element down, does not come in same level
I have created a container and three divs inside that. The first two divs are inside a for loop, the data is coming from backend (django) and the number of divs is created accordingly. The right div is a place where I want to place some elements, which should be at same level but it's coming at the very bottom of the container div. HTML : <form method="POST" action="runrobo" name="runrobomain"> <div id="container_runrobo"> <div id="runrobo_left"><b>Test Suite Name</b></div> <div id="runrobo_center"><b>Order (Priority)</b></div> {% for suite_name in data %} <div id="runrobo_left"> <input type="checkbox" name="suite_checkbox" value="{{ suite_name }}">&nbsp;{{suite_name}} </div> <div id="runrobo_center"> <input type="text" name="suite_order"> </div> {% endfor %} <div id="runrobo_right"> <b>More Config Options</b> </div> </div> </form> CSS : #container_runrobo { width: 90%; margin-left: 1%; background-color: lightgray; border: 1px solid black; } #runrobo_left { float: left; width: 30%; padding: 5px; border: 1px solid black; } #runrobo_center { margin: 0 auto; width: 30%; padding: 5px; border: 1px solid black; } #runrobo_right { float: right; width: 30%; border: 1px solid black; } Now, after googling a lot, I added another div after the right one : <div style="clear: both;>&nbsp;</div> But that too did not solve my problem.