Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Error in python commands after install virtualenv
I had installed python and django whithnout virtualenv and worked with it. Now I have install virtualenv and my python command don't work!!! For example : C:\Users\omid>pip install django Fatal error in launcher: Unable to create process using '"' why this error is display ??? Is problem with virtualenv? -
How to set index page with path function in django 2.0?
Django 2.0 has introduced new path function in django.urls. So I m using path function to set my index page but as far as I know it doesn't accept regular expression.I have tried couple of options as follows path('/',views.index,name='index'), and path('/index',views.index,name='index'), but it gives 404 page not found. So my question is how to set index page site using path function? -
is it possible to append templates in django
I'm trying to display 2 views on the same page (both from different apps) I've imported the views into a third app which I want to use to put the 2 files together. At the moment I'm able to show 1 of the 2 apps. I'm retreving the views of the app like this: def bar(request): # Get the template template = loader.get_template('topbar.html') #render the template and store the outcome in 'render' render = template.render({}, request) #return the rendered template return render after this I can get this view from another app like this: render = bar(request) return HttpResponse(render) this works and the html file is showing nicely but now I want to append the second view (which can be requested in the same way) to the first one. Is this possible? Am I doing it the right way? -
Django RestframeWork Serializer relations , How to get the data of both of One to One Models?
The mode is: class Userinfo(models.Model): class Meta: verbose_name='用户信息' verbose_name_plural='用户信息' user=models.OneToOneField( User, related_name='userinfo', on_delete=models.CASCADE, verbose_name='用户' ) location=models.BooleanField(verbose_name='地点(勾选宏达,否则福年)') And the Restframework Token class: @python_2_unicode_compatible class Token(models.Model): """ The default authorization token model. """ key = models.CharField(_("Key"), max_length=40, primary_key=True) user = models.OneToOneField( settings.AUTH_USER_MODEL, related_name='auth_token', on_delete=models.CASCADE, verbose_name=_("User") ) created = models.DateTimeField(_("Created"), auto_now_add=True) My serializers is: class UserinfoSerializer(serializers.ModelSerializer): class Meta: model=Userinfo fields="__all__" class UserSerializer(serializers.ModelSerializer): class Meta: model=User exclude=('password',) userinfo=UserinfoSerializer() class TokenSerializer(serializers.ModelSerializer): class Meta: model=Token fields = '__all__' depth=3 user = UserSerializer() I want to Response the data of User and the One to One Model Userinfo,but I just get the user. what can I to? Here is my current result,and The userinfo is null, How can I get the userinfo data? { "key": "2012964fb4ffe07dc58c33a64d0ce48bedd34643", "user": { "id": 3, "userinfo": null, "last_login": null, "is_superuser": false, "username": "333", "first_name": "叶同学", "last_name": "", "email": "", "is_staff": false, "is_active": true, "date_joined": "2017-12-08T16:39:00+08:00", "groups": [], "user_permissions": [] }, "created": "2017-12-14T10:40:58.933072+08:00" } -
Type of obj argument in SerializerMethodField DRF
I have this Django REST Framework serializer class: class DoctorMeetingSerializer(serializers.ModelSerializer): doctor_id = serializers.CharField() patient_id = serializers.CharField() meetings_amount = serializers.SerializerMethodField() class Meta: model = CoachingMeeting fields = ( 'id', 'doctor_id', 'patient_id', 'start_time', 'end_time', 'subject', 'meetings_amount', ) read_only_fields = ('zoom_meeting_id', 'is_live', 'meetings_amount',) def get_meetings_amount(self, obj): print(type(obj)) meetings_amount = DoctorMeeting.objects.filter(patient=obj.patient_id).count() return meetings_amount So when I do GET request, print(type(obj)) shows that obj is serializer instance, but then I do POST request, obj becomes an OrderedDict instance and has no 'patient_id' attribute. Why does this object changes its type in different request methods? -
context not rendering in django App
I am driving to render a context scale that is not rendering in my HTML and I can manage to see the error. I do not get any error in the inspect/console and neither in the Atom terminal. I am developing a survey app using a scale from 0-100% (using JavaScript) but for some reason it is not rendering; here is my code: views.py class SurveyDetail(View): def get(self, request, *args, **kwargs): survey = get_object_or_404(Survey, is_published=True, id=kwargs['id']) if survey.template is not None and len(survey.template) > 4: template_name = survey.template else: if survey.display_by_question: template_name = 'survey/survey.html' else: template_name = 'survey/one_page_survey.html' if survey.need_logged_user and not request.user.is_authenticated(): return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path)) categories = Category.objects.filter(survey=survey).order_by('order') form = ResponseForm(survey=survey, user=request.user, step=kwargs.get('step', 0)) try: get_scale = form.get_multiple_scale() except: get_scale = None context = { 'response_form': form, 'survey': survey, 'categories': categories, 'scales': get_scale } return render(request, template_name, context) form.py: class ResponseForm(models.ModelForm): WIDGETS = { Question.TEXT: forms.Textarea, Question.SHORT_TEXT: forms.TextInput, Question.RADIO: forms.RadioSelect, Question.SELECT: forms.Select, Question.SELECT_IMAGE: ImageSelectWidget, Question.SELECT_MULTIPLE: forms.CheckboxSelectMultiple, Question.SCALE: forms.TextInput, } class Meta(object): model = Response fields = () def __init__(self, *args, **kwargs): """ Expects a survey object to be passed in initially """ self.survey = kwargs.pop('survey') self.user = kwargs.pop('user') try: self.step = int(kwargs.pop('step')) except KeyError: self.step = None … -
How to unsign signed cookie manually
I am using Django version 1.11.2 and using signed cookies for session store. SESSION_ENGINE = "django.contrib.sessions.backends.signed_cookies" I am trying to unsign the cookie using python shell using: from django.core import signing signing.loads(".eJxVjk0.....J708kRdRvubY3RME") but I get BadSignature error. May be I am using the signing.loads in wrong way? -
syntax error for manag.py migration error in django
when I try to make migration it shows me a error File "manage.py", line 10 except ImportError: ^ SyntaxError: invalid syntax enter image description here -
Trying to install latest version of Django
In my cmd i was using python2.7 because i have both python 2.7 and python 3.6 installed.I installed django with pip but pip installed django 1.11.11 because i was using python 2.7.I want to use python 3.6 and the latest version of django so im now using python3.6 in the cmd.I uninstalled django and then installed it while using python3.6.But when i tried to install django with pip it said that some directory is not empty.What can i do?I uninstalled django why the directory is not empty?