Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django login form: where have I gone wrong?
Really not sure what is wrong with my login form and view...I will display it here in the hope that someone may know roughly where I have gone wrong: Essentially on "submit" - the control flow doesn't break into the form.is_valid nest... views.py: def login_view(request): title = "login" form = UserLoginForm(request.POST or None) context = { "form": form, "title": title } print(request.user.is_authenticated()) if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(username = username, password = password) login(request, user) print(request.user.is_authenticated()) if username == "": error = "Please enter a username..." context = { "form": form, "title": title, 'error': error } if password =="": error = "Please enter a password..." context = { "form": form, "title": title, 'error': error } #If a password and username exists lets see if we can authenticate it: if username and password: if user is not None: #Checking if the user exists and the user is not none, if so continue, else raise an active user error: if user.is_active: #Check that the password is correct and matches up to the password in the User.user model: if user.check_password(password): if user: #One further check to see if user is true, if so let's login them in: #Let's … -
django el-pagination pagination issue
i am using django el-pagination for ajax pagination.My django version is 1.11.1.The problem i am facing is that during pagination,whole template is being loaded into the div.I have tried many solutions but all in vain.For view,i am NOT using the check request.is_ajax as it seems that this issue is related to js.My js code is $('#dashboardTable').endlessPaginate({ pageSelector: '#dashboardTable' }); #dashboardTable is div in which table html file is included.Also on dashboardTable the class endless_page_template is being applied.This is simply driving me thinking that is there not a single library for django which does not contains any bugs!.Thanks -
Django REST, Accessing methods of the selected object
this part of my code fills the queryset with [category_object].subcats.all(). let it subcats be a method of category object: serializer: class CatSrlz(serializers.ModelSerializer): class Meta: model = Category fields = ('id', 'label', ) View: class CatsViewSet(viewsets.ReadOnlyModelViewSet): queryset = Category.objects.filter(parent=None) serializer_class = CatSrlz def retrieve(self, request, *args, **kwargs): # return Response({'res': self.kwargs}) queryset = Category.objects.get(pk=str(self.kwargs['pk'])).subCats.all() dt = CatSrlz(queryset, many=True) return Response(dt.data) and url: router.register(r'cats', views.CatsViewSet) it works but i'm pretty sure that there must be a more correct way of doing so Is there one? thanks -
Template variables based on calculations using fields from Django Model
I am using Django 1.10.7 and Python 3.6.1. First my code, then my questions. My model looks like this: class Thing(models.Model): user = models.ForeignKey('auth.User') title = models.CharField(max_length=200) start_date = models.DateTimeField( default=timezone.now) cost_per_day = models.DecimalField(max_digits=6, decimal_places=2) Here are my views: def something_list(request): things =Thing.objects.filter(start_date__lte=timezone.now()).order_by('start_date') return render(request, 'myApp/something_list.html', {'things': things}) def thing_detail(request, pk): thing = get_object_or_404(Thing, pk=pk) return render(request, 'myApp/thing_detail.html', {'thing': thing}) I have two template blocks for each of these views, where I am using template tags to display variables. For example: <h2 class="title"><a href="{% url 'thing_detail' pk=thing.pk %}">{{ thing.title }}</a></h2> <p>User: {{ thing.user }}</p> <div class="date"> <p>Start Date: {{ thing.start_date }}</p> </div> <p>Cost per day: ${{ thing.cost_per_day }}</p> So what is happening here? Web users can enter what I am calling any number of "Things" with 4 fields: User, Title, Start Date, and Cost per Day. I have TWO calculations that I would like to make, and render them in the template. Problem 1) The user needs to see how many days have elapsed since they originally entered a Start Date. The calculation will be a subtraction of the current time/date (Now) and the Start Date. I was able to accomplish this by using the Django timesince feature shown here: … -
Django Query that gets objects based latest foreign key timestamp and orders them
I am looking to order a queryset based on a set of objects timestamp. Here's a simplified example: Class Device(models.Model: status = models.CharField(max_length=50) class Event(models.Model): timestamp = models.DateTimeField(auto_now_add=True) device = models.ForeignKey(Device) I want to get the latest Event of the device so I can order a Device queryset based on that. -
Django class based generic view “CreateView” form errors handling
I am new to CBV and am trying to use the generic view CreateView and understand it. In models.py I have this model: class CartConfig(models.Model): cart_key = models.CharField( 'Chave do Carrinho', max_length=40, db_index=True ) PAYMENT_OPTION_CHOICES = ( ('cash', 'Dinheiro'), ... ) payment_option = models.CharField( 'Opção de Pagamento', choices=PAYMENT_OPTION_CHOICES, max_length=20, default='cash' ) address = models.ForeignKey(Address, verbose_name='Endereço de entrega', blank="false") class Meta: verbose_name = 'Configuração do carrinho' verbose_name_plural = 'Configurações do carrinho' def __str__(self): return 'Cart configs for {}'.format(self.cart_key) That model uses a ForeignKey to Address, which is also a ManyToManyfield in the User model. So, in my views.py I edited the queryset of ´adress´ field to handle only the address relationed to the current User: class CartConfigView(CreateView): model = CartConfig template_name = 'checkout/cart_config.html' fields = ['address','payment_option'] success_url = reverse_lazy('index') def get_context_data(self, **kwargs): context = super(CartConfigView, self).get_context_data(**kwargs) context['form'].fields['address'].queryset = get_object_or_404(User, pk=self.request.user.pk).address.all() context['form'].fields['address'].empty_label = None return context In my template it works fine, show the right address list and creat it as well through the post form. But if the user don't select an address, it triggers the expected error NOT NULL constraint failed: checkout_cartconfig.address_id. The question is, should not the CreateView handles this error? What am I doing wrong? How can I … -
Django : How to import a python module such as pytube into a static template/webpage?
I am very new to Django. Recently I was developing a site just for getting aquainted with the framework and I came to a point where I needed to import a python module such as request,pytube etc into a static webpage so that i can use their functions . So two questions arose - 1. Is it possible to have python code embedded in static content. 2. How can I import a python module into a static webpage. -
Update several records at once using Django
I want to know a way on how to update the data once is edited from the input boxes all with one click. I found this post on how to do it with checkboxes: Updating several records at once using Django but I'm not sure how to do it for input boxes. here is my code: <table class="table table-striped table-bordered table-hover dataTables-example" > <thead> <tr> <th>Local</th> <th>line</th> <th>rack</th> </tr> </thead> <tbody> {% for linea in lineas_de_reporte %} <tr> <td>{{ linea.local }}</td> <td><input type="text" name="case-opened" value="{{ linea.rack }}" id="caseOpened"/></td> <td><input type="text" name="case-opened" value="{{ linea.line }}" id="caseOpened"/></td> </tr> {% endfor %} </tbody> Here is how it looks: Is there a way bu just sending all the values (by id) to a function in a list using Django? EDIT: forms.py class TVSForm(forms.Form): rack = forms.CharField() line = forms.CharField() -
Django filter queryset __in for *every* item in list (2.0)
I've already read this and this But the "final" comparison of the number is hard-coded. I have some Ingredients, and a Recipe like this: class Ingredient(models.Model): label = models.CharField(max_length=200, null=True, blank=True, default=None) description = models.TextField(null=True, blank=True, default=None) class Unit(models.Model): label = models.CharField(max_length=200, null=True, blank=True, default=None) abbr = models.CharField(max_length=20, null=True, blank=True, default=None) class IngredientUnit(models.Model): ingredient = models.ForeignKey(Ingredient, null=False, blank=True) unit = models.ForeignKey(Unit, null=False, blank=True) measurable = models.BooleanField(default=True, null=False, blank=True) is_int = models.BooleanField(default=True, null=False, blank=True) value = models.FloatField(null=True, blank=True, default=0.0) class Recipe(models.Model): label = models.CharField(max_length=200, null=True, blank=True, default=None) description = models.TextField(null=True, blank=True, default=None) ingredients = models.ManyToManyField(IngredientUnit) I'd like to do this: 'select all recipe that have all' the ingredient of an array of ingredient's pk. So far I've done this but it's not working. ingredient_ids = self.request.POST.getlist('ingredient[]', []) if len(ingredient_ids): recipes = Recipe.objects\ .filter(ingredients__in=ingredient_ids)\ .annotate(nb_ingredients=Count('ingredients'))\ .filter(nb_ingredients=len(ingredient_ids)) print([a for a in recipes]) the problem is that nb_ingredients=len(ingredient_ids) should be nb_ingredients=the number of the ingredients of the current recipe How to do this? -
How to override null and blank field attributes of an abstract model
I want to set null and blank to true on all the fields inherited from an abstract model. My current attempt follows similar SO questions, e.g. overriding the 'default' attribute on ABC and overriding parent model's attribute, which say it is possible. I get the required runtime behaviour, when initialising objects from the python console, but it is not reflected in the migrations file or database. Context: I have a System model where I want to be able to create client specific overrides on certain data. I have the following models: abstract BaseSystem - defining the overridable fields concrete SystemOverride - containing the partially overridden records concrete System - containing the 'full' System records. It is important to make all the fields in SystemOverride null/blank = True so that only the fields that are initialised (by the client) will override the related System object. Code: class BaseSystem(models.Model): class Meta: abstract = True def __init__(self, *args, **kwargs): super(BaseSystem, self).__init__(args, kwargs) # Mark all fields with 'override' attribute for field in self._meta.get_fields(): field.override = True name = models.CharField(max_length=128) class System(BaseSystem): pass class SystemOverride(BaseSystem): def __init__(self, *args, **kwargs): super(SystemOverride, self).__init__(args, kwargs) # Set all overridable fields to null/blank = True. for field in … -
Django gettext doesn't works
I try to serve my django-cms website in multiple languages makemessages and compilemessages works like a charm, but when I runserver , my strings stay untranslated The python files where i used ugettext_lazy: from cms.toolbar_pool import toolbar_pool from cms.extensions.toolbar import ExtensionToolbar from django.utils.translation import ugettext_lazy as _ from .models import CategoryExtension @toolbar_pool.register class CategoryExtensionToolbar(ExtensionToolbar): # defines the model for the current toolbar model = CategoryExtension def populate(self): # setup the extension toolbar with permissions and sanity checks current_page_menu = self._setup_extension_toolbar() # if it's all ok if current_page_menu: # retrieves the instance of the current extension (if any) and the toolbar item URL page_extension, url = self.get_page_extension_admin() if url: # adds a toolbar item in position 0 (at the top of the menu) current_page_menu.add_modal_item(_('Page Category'), url=url, disabled=not self.toolbar.edit_mode, position=0) My settings related to translations : def gettext(s): return s LOCALE_PATHS = ( BASE_DIR + "/locale", ) LANGUAGE_CODE = 'fr-fr' TIME_ZONE = 'Europe/Paris' USE_I18N = True USE_L10N = True USE_TZ = True LANGUAGES = ( ('fr-fr', gettext('fr-fr')), ) CMS_LANGUAGES = { 1: [ { 'code': 'fr-fr', 'name': gettext('fr-fr'), 'redirect_on_fallback': True, 'public': True, 'hide_untranslated': False, }, ], 'default': { 'redirect_on_fallback': True, 'public': True, 'hide_untranslated': False, }, } And my po file (in PROJECT_ROOT/locale/fr-fr/LC_MESSAGES/django.po) … -
I've tried to bypass ManyToMany relation between 2 models in Django but not sure that it's correct
I'm learning Django,but i don't understand the models.ManyToManyField.So,to bypass i've tried to create 3 models.A,B and C.A and B are the to models which should be in models.ManyToManyField relationship.As i don't understand how it work,i've create a third model called C.And my C model receives 2 Foreign keys coming from A and B,it's the table which puts A and B in a ManyToMany relashionship.I've tried to insert data,and all seems okay.Here is my test code class A(models.Model): a_name=models.CharField(max_length=50) def __str__(self): return self.a_name class B(models.Model): b_name=models.CharField(max_length=50) def __str__(self): return self.b_name #The table which links A and B with Many to Many relationship and receive A and B Foreign Keys class C(models.Model): a=models.ForeignKey(A,on_delete=models.CASCADE) b=models.ForeignKey(B,on_delete=models.CASCADE) c_name=models.CharField(max_length=50) def __str__(self): return self.c_name I think that it's specially help when table C model also has attributes.How do you find the idea?Will it create problems in a more complex web app or i can keep on working that way? -
Does rest_framework coreapi not support PUT / PATCH?
I'm wanting to use the Python Client Library, but having no end of pain getting PUT/PATCH to work. Whenever I try using update / partial_update, the URL param isn't interpolated from the dictionary, and the server returns a 404. [06-Jun-2017 12:30:05] WARNING [django.server:124] "PUT /api/accounts/networks/%7Bcid%7D/ HTTP/1.1" 404 23 Which clearly shows that the {cid} param was never replaced with the actual value. Which brings me to the TL/DR version of my question, does CoreAPI not support PUT / PATCH? The PUT / PATCH options are correctly setup, according to this info: GET /api/accounts/networks/2892c424-3a86-16bb-8b60-12a79900e90c/ HTTP 200 OK Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "url": "http://localhost:8000/api/accounts/networks/2892c424-3a86-16bb-8b60-12a79900e8fb/", "created": "2016-04-16T19:35:02.169898Z", "modified": "2017-05-30T17:25:29.768740Z", "cid": "2892c424-3a86-16bb-8b60-12a79900e8fb", "name": "10.0.0.0/8", "comments": "Local Area Network - 10.x", "builtin": true } Now that I've blown most of a morning trying to make this work, I realize that there's no documentation example showing update / partial update. So I thought I'd try using coreapi-cli instead, but I have the same problem. coreapi action networks partial_update --param cid='2892c424-3a86-16bb-8b60-12a79900e8fb' --param comments='this is WAAAY too hard' <Error: 404 Not Found> detail: "Not found." Django's logline shows that the URL param was never substituted from the 'cid' param provided: … -
Fuzzy search in django 1.10 with haystack 2.6 and elasticsearch 2.4
I'm trying to use the fuzzy search capabilities of haystack 2.6 (described to some extent in How can I do a fuzzy search using django-haystack and the elasticsearch backend?) I've tried SearchQuerySet().filter(content__fuzzy='djangu') hoping to gets hits for django but the query returns no results. My application uses django 1.10, elasticsearch 2.4, haystack 2.6 There is an old question on the topic How can I do a fuzzy search using django-haystack and the elasticsearch backend? but I'm hoping there is now an easier way to go about things. Thanks! -
Best to inherit methods from another class to multiple subclasses in django
I have multiple subclasses that uses very similar methods with differing arguments I want to pass.For instance I'm using the parent subclass SportsSentiment that contains a function that returns all the rows for an individual league (NBA, NFL, MLB...etc) Here is the Parent Class: from django.db import models from sports_sentiment.main.models import SentimentPoint class SportsSentimentMixin(models.Model): test = "abc" # I want my subclasses to inherit this method! def get_league_sentimental_points(self, league): return SentimentPoint.objects.all().filter(league=league) class Meta: abstract = True An example of a subclass: from sports_sentiment.custom_mixins import SportsSentimentMixin class NBASportsSentimentView(TemplateView, SportsSentimentMixin): template_name = 'NBA/sports_sentiment.html' # This doesn't work, but I'm trying to get the the # the function get_league_sentimental_points from the parent # class nba_data = self.get_league_sentimental_points("NBA") -
Django and woocommerce
I am trying to use the REST api to link a wordpress e-commerce (using woocommerce) website and a Django app. My question is, how can I execute a python script inside Django, and return data after a purchase has been made on the e-commerce website. -
Django/React Native/OAuth: Best way to handle Auth flow?
So I'm trying to integrate a Django/Python backend framework with a React Native frontend, and I was wondering if there are any good resources/answers out there to handle OAuth flow? I've tried a lot of different aspects, and from the server side at least, the best thing that possibly worked is OAuth Toolkit. I also want to use Django REST framework to exchange data between server/client. However, I am confused about the flow of authentication between the app and the server and would appreciate a better understanding. Thanks! -
MS Windows, virtual environment, manage.py "Couldn't import Django"
When running manage.py runserver, I get the following error: "Couldn't import Django. Are you sure it's installed and " Import Error: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?" My research (eg https://groups.google.com/forum/#!topic/django-developers/aXF1j55hb2Q) says this is usually a problem with either not running a virtual environment, or not installing django with pip. The questions I've find on StackOverflow receiving this error (eg Django installation on MS Windows, manage.py "Couldn't import Django") have been resolved with one of those two fixes. I installed django in my virtual environment, and am attempting to run manage.py within that virtual environment. Django was installed with pip3. I cannot find any suggestions to troubleshoot this problem other than those two. What's the next thing to try? -
Django: To use User model or Profile model for related models
General question here (more specifically for Django/Python), when creating a model such as a Company for example, and several users (employees) are going to be related to such model, how should the different models be related? I.e. a user profile will be related to a user object via a OneToOneField. But should the Company object be related by a ForeignKey to the User object or the UserProfile object, and why is this the appropriate way? So class UserProfile(models.Model): # For the Company Employees user = models.OneToOneField(UserModel, related_name='employeeprofilemodel', on_delete=models.CASCADE, blank=True, null=True) ... company_rel = models.ForeignKey(CompanyModel, related_name='companyrel', null=True) or class User(AbstractBaseUser): # For all Users ... company_rel = models.ForeignKey(CompanyModel, related_name='companyrel', null=True) -
Template Tag not working with csrf_token
I am attempting to create a custom template tag to display a comment. When I try submitting a reply through the form attached to each comment, I get an error: Forbidden (403) CSRF verification failed. Request aborted. Reason given for failure: CSRF token missing or incorrect. The csrf token works on the form with the download and follow button, but not on the form generated from the template tag. Any help would be appreciated. DocumentView def DocumentView(request, doc_id): context = {} user = None if request.user.is_authenticated(): email = request.user.email id = request.user.id user = get_user_information(email=email) else: user = None context['user'] = user if request.method == 'POST': user_id = request.POST.get('submit', '') doc = Doc.objects.get(id=doc_id) doc_version = DocVersion.objects.filter(doc__id=doc_id).latest('id') doc_title = doc.response_title allow_comments = doc.allow_comments comments = {} if user['user_type'] == 'DA': for comment in Comment.objects.filter(doc_id=doc_id): comments[comment.id] = {'content': comment.content, 'reply_to': comment.reply_to, 'user_id': comment.user.id} else: for comment in Comment.objects.filter(doc_id=doc_id, is_flagged=False): comments[comment.id] = {'content': comment.content, 'reply_to': comment.reply_to, 'user_id': comment.user.id} context['comments'] = comments context['allow_comments'] = allow_comments context['doc_title'] = doc_title print context return render(request, 'doc/document.html', context) comment_tags.py from django.template import Library, Node, Context, Variable from django.template.loader import get_template from django import template register = Library() @register.tag() def comments(parser, token): user_id, profile_pic, reply_id, comment_id, content, info = … -
Django forms - rendering form and redirecting
I am trying to create an 'add user' feature which will simply add the user you've selected from a dropdown as your connection. I am using ModelChoiceField from Django Forms so that I may get the existing users from my User model in the dropdown. forms.py from django import forms from django.contrib.auth.models import User class NetworkForm(forms.Form): user_id = forms.ModelChoiceField(queryset=User.objects.all(), label='', widget=forms.Select(attrs={'class': 'all_users'})) views.py @login_required def index(request): user_list = User.objects.exclude(username=request.user) return render(request, 'chat/index.html', {'user_list': user_list}) For now I am just printing the form to see output @login_required def add_user(request): form = NetworkForm() if request.method == 'POST': form = NetworkForm(request.POST) if form.is_valid(): print form return redirect(request.META['HTTP_REFERER']) errors = form.errors or None return render(request, 'chat/index.html', { 'form': form, 'errors': errors, }) index.html <div class="row"> <form action="{% url 'chat:add_user' %}" method="post"> {% csrf_token %} {{ form.as_p }} <button class="btn btn-warning" value="{{ user_id }}" style="float: left;">Submit</button> </form> </div> urls.py urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^add_user/$', views.add_user, name='add_user'),] The way it is being rendered currently is: I have my main index page where I don't see any dropdown, i.e., When I click on the submit button, it moves me to index/add_user, where I get a dropdown with user (with a warning "this field is required) … -
Django- Disabling confirm password
I followed following documentation : Custom user model with email as primary login field. The documentation is too good. Here two password fields are used. I don't want to use confirm password. I only want to use single password field. Is there any way to do that? -
Python3: ImportError / SystemError when importing custom modules
Context Yes, I know there are a lot of SO questions out there address either the first or latter part of my question. To be honest, I have not read all of them. However, I did read several good ones (such as this) as well as PEP328. Many of the questions I have read, more often than not, are regarding the lack of an __init__.py file. Then many address not having the proper directory in sys.path or $PYTHONPATH. A few were in regards to syntax relating to relative imports. So while this is probably a duplicate, please consider helping me learn why the same command - from my_module.my_class import MyClass - works in one context and not the other (despite having the sys.path correct) I am using Django. Prior to using Django I exclusively used absolute imports, however this caused a problem with Django that quickly was solved by use of relative imports as I learned here. Current Issue My current issue is that relative imports do not seem to be working consistently. For example, consider: my_module ---- __init__.py ---- my_sub_class.py ---- my_class.py ---- some_functions.py Inside my_class.py: from .my_sub_class import MySubClass class MyClass(): self.subclass = MySubClass() and inside some_functions.py from … -
django: Why do we use a nested meta class inside modelSerializer?
I am new to python as well as to django and learning about serializers. I observed that While defining a serializer class it needs a nested meta class inside it. I am not good with this meta class concept, so i googled about it and found that metaclass is a class whose instances are classes. Even after reading that i am confused. Is the outer serializer class an instance of the inner meta class here? What is the need of using this meta class here? -
monolithic or microservice concept
I have a very large django project with many features that uses django as backend framework. My project lets users use both a website and a iOS app. I am researching using a monolithic app (currently using monolithic) vs micro services, I watched this video but one part really throws me off. At 1:05, he previews his 'monolithic' app before he changes to micro services, which to me looks like a single project with a bunch of different apps. 1) Are these technically just folders and not apps? These (what i would assume he calls folders) all have a models.py and views.py and most have a admin.py. 2) What makes this a monolithic app? Is it just because he doesn't simply use django-admin startapp in the terminal to create these 'folders'? 3) Or are microservices multiple projects connected and not simply multiple apps in a single project? My biggest confusion is with the previewed project in the video because before then I thought I had a good grasp on these concepts. I was simply looking to change to microservices, after this part in the video I'm not sure I even know what a monolithic app really is.