Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to query number of input based on minute in Django?
So i'm implementing a webapps for a local trucking rental SME. basically what it does is it logs date, hour and minutes to count the Ritase(the output) of the truck. here is models.py class Muatan(models.Model): recorded_date = models.DateField(auto_now_add=True) date_added = models.DateField(auto_now_add=False) shift = models.ForeignKey(Shift, on_delete=models.DO_NOTHING) time_logged = models.TimeField(auto_now_add=False) excavator = models.ForeignKey(Excavator, on_delete=models.DO_NOTHING) operator_excavator = models.ForeignKey(ExcavatorOperator, on_delete=models.DO_NOTHING) dumpTruck = models.ForeignKey(DumpTruck, on_delete=models.DO_NOTHING, null=True) driver_dumptruck = models.ForeignKey(DumpTruckDriver, on_delete=models.DO_NOTHING) location = models.ForeignKey(Lokasi, on_delete=models.DO_NOTHING) material = models.ForeignKey(Material, on_delete=models.DO_NOTHING) reported_problem = models.TextField(blank=True) to give an example from the models, suppose that the manager logs these input from admin.py august 13, 2018 at 14:20 august 13, 2018 at 14:40 august 13, 2018 at 14:59 august 13, 2018 at 15:15 august 13, 2018 at 15:30 the expected output from the query would be something like hour: 14 mins: 20 hour: 14 mins: 40 hour: 14 mins: 59 total ritase: 3 because there are 3 logs within the hour 14. how would i implement this in django? also, do i put the code in models.py or views.py? total django noobs here, really appreciate your help SO :) -
Django social_django 'Specifying a namespace in include() without providing an app_name '
When I am trying to run python manage.py makemigrations The following error is shown, path('account/', include('django.contrib.auth.urls', namespace='auth')), File "/home/barsmansvps/DataScience/anaconda3/lib/python3.6/site-packages/django/urls/conf.py", line 39, in include 'Specifying a namespace in include() without providing an app_name ' django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. Here is my project urls.py file, from django.contrib import admin from django.urls import path, include # For google login from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', include('home.urls')), # path('', include('pages.urls')), path('products/', include('products.urls')), path('reports/', include('reports.urls')), path('account/', include('social_django.urls', namespace='social')), path('account/', include('django.contrib.auth.urls', namespace='auth')), path('admin/', admin.site.urls), ] -
Django 2.0 get value from ForeignKey in template
I want to display the associated phone number with the announcement in the template, but the only thing I see is the empty space models.py class Announcement(models.Model): title = models.CharField(max_length=70) user_profile = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='user_profile') class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone_number = models.CharField(max_length=12) def get_phone_number(self): return self.phone_number views.py class AnnouncementListView(ListView): model = Announcement template_name = 'app/categories/announcement.html' def get_queryset(self): return Announcement.objects.filter(subcategory_id = self.kwargs['subcategory_id']) template {% for article in object_list %} {{ article.title }}(working) {{ article.user_profile.phone_number }}(not working) {{ article.user_profile.get_phone_number }}(not working) -
get_current_user() in Django not working
I'm working on a Django application. I'm trying to import get_current_user class from .utils module. But it is not importing it. It's not able to find the class and giving error. Unresolved reference 'get_current_user' less I'm using Django version 2.0.7 and I couldn't find proper documentation related to get_current_user on internet or official site. Someone please help me out. -
Create database view from django model
I learned sql "view" as a virtual table to facilitate the SQL operations, like MySQL [distributor]> CREATE VIEW CustomerEMailList AS -> SELECT cust_id, cust_name, cust_email -> FROM Customers -> WHERE cust_email IS NOT NULL; Query OK, 0 rows affected (0.026 sec) MySQL [distributor]> select * from customeremaillist; +------------+---------------+-----------------------+ | cust_id | cust_name | cust_email | +------------+---------------+-----------------------+ | 1000000001 | Village Toys | sales@villagetoys.com | | 1000000003 | Fun4All | jjones@fun4all.com | | 1000000004 | Fun4All | dstephens@fun4all.com | | 1000000005 | The Toy Store | kim@thetoystore.com | | 1000000006 | toy land | sam@toyland.com | +------------+---------------+-----------------------+ 5 rows in set (0.014 sec) When I checked the Django documentation subsequently, there are no such functionality to create a virtual "model table" which could simplify the data manipulation. Should I forget the virtual table "view" when using Django ORM? -
How to translate Django messages depending on the language selected
Hello I have a multy lingual project in Django. I have done the translations with USE_I18N. Everything works fine in the templates with the {% trans 'hello world' %} but how should I process the messages? when I send messages.warning(request, "Невалиден имеил или парола") I want it to be translated in english if the language selected is english -
Manipulating default django stdout logs
Whenever I visit my django admin I see this in my logs [2018-08-13 15:41:55 +0800] [95] [DEBUG] GET /admin/login/ 172.18.0.4 - - [13/Aug/2018:15:41:55 +0800] "GET /admin/login/?next=/admin/ HTTP/1.0" 200 1859 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36" [2018-08-13 15:41:55 +0800] [95] [DEBUG] Closing connection. I want to manipulate the line which displays 172.18.0.4 - - [13/Aug/2018:15:41:55 +0800] "GET /admin/login/?next=/admin/ HTTP/1.0" 200 1859 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6). How can I change the format of that part? -
How to filter posts with no comments
Let's get to the problem. I have a view that is supposed to show me all unanswered questions, that were asked later 4 hours. I' ve already tried a lot but it didn't work, so i ask this. What should I do to filter posts without comments views.py def subject_unanswered(request, slug): subject = Subject.objects.filter(slug=slug).first() four_hours = datetime.today() - timedelta(hours=4) posts = Post.objects.filter(subject=subject, created_at__lt=four_hours).order_by('-created_at') args = { 'subject' : subject, 'posts' : posts, } return render(request, 'ask/subject_time_ago.html', args) models.py class Comment(models.Model): related_post = models.ForeignKey(Post, on_delete=models.CASCADE) comment = models.TextField(max_length=1000) created_by = models.ForeignKey(MyUser, on_delete=models.CASCADE, related_name='comments') created_at = models.DateTimeField(auto_now_add=True) likes = models.ManyToManyField(MyUser, related_name='comment_likes', blank=True) class Post(models.Model): slug = models.SlugField(unique=True, max_length=200) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) topic = models.CharField(max_length=200) text = models.TextField(max_length=5000) created_by = models.ForeignKey(MyUser, on_delete=models.CASCADE, related_name='posts') created_at = models.DateTimeField(auto_now_add=True) likes = models.ManyToManyField(MyUser, related_name='likes', blank=True) -
recursions or itertool instead of for loop
my code is like this. def get_group_last111(group): groupmap = services_models.GroupMapping.objects.filter(parent_id=group) group_list = [group.id] for each in groupmap: group_list.append(each.group_id) groupmaploop = services_models.GroupMapping.objects.filter(parent_id=each.group_id) if groupmaploop.exists(): for each_data in groupmaploop: group_list.append(each_data.group_id) groupmaploop1= services_models.GroupMapping.objects.filter(parent_id=each_data.group_id) if groupmaploop1.exists(): for each_data1 in groupmaploop1: group_list.append(each_data1.group_id) groupmaploop3= services_models.GroupMapping.objects.filter(parent_id=each_data1.group_id) if groupmaploop3.exists(): for each_data2 in groupmaploop1: group_list.append(each_data2.group_id) groupmaploop4= services_models.GroupMapping.objects.filter(parent_id=each_data2.group_id) if groupmaploop4.exists(): for each_data5 in groupmaploop4: group_list.append(each_data5.group_id) print set(group_list) return set(group_list) can i do this more efficiently using itertool or recursive function.please help me -
How can I make the M2M relation to be a mandatory field?
I have 2 models Product and Category class Product(models.Model): categories = models.ManyToManyField(Category, related_name='products') By default Django doesn't throw a validation error if no category is introduced. How can I make the M2M relation to be a mandatory field ? -
Create user Authentication dashboard using Django or Dash/ Plotly
1) I'm working on a project where a sub task is to create a user authentication step which needs to have the login and signup process as well as the logout process. 2) Along with this, I would also need the users online and number of users in the application. I'm planning to work in one of Django or Dash/ plotly in Python and I'm using Jupyter notebook to work with. I have already went through one of Dash Authentication samples in the site below, https://dash.plot.ly/authentication but I'm not able to run through the 2nd example which is Plotly OAuth Example, where I'm facing the below error: ConnectionError: HTTPSConnectionPool(host='api.plot.ly', port=443): Max retries exceeded with url: /v2/files/lookup?path=Dash%20Authentication%20Sample%20App (Caused by NewConnectionError(': Failed to establish a new connection: [Errno 11004] getaddrinfo failed',)) I'm looking for inputs/ resources to best work with this project. Any help/ suggestions are really appreciable and thankful. -
Django why is my project_form not working?
So I've been trying to implement a way to post a project, like a blog. It will have a thumbnail, title, description, and screenshots. I got the multiple image upload working, which falls in the p_formset. But whenever I make an if statement for both project_form and p_formset being valid it is not working. I assume it is the project_form with issue but I am not sure. Nothing happens in the page anymore. My code is below: views.py from django.shortcuts import render, redirect, reverse,get_object_or_404 from django.utils import timezone from django.core.files.base import ContentFile from django.forms import modelformset_factory from django.http import JsonResponse from django.views.decorators.http import require_http_methods from django.views import View from .models import Projects, P_Images from .forms import ProjectsForm, P_ImageForm # Create your views here. # Function to create projects class CreateProjectsView(View): def get(self, request): p_photos = P_Images.objects.all() project_form = ProjectsForm(request.GET) #project_form = ProjectsForm(request.GET) context = { 'p_photos': p_photos, 'project_form': project_form, } return render(self.request, 'projects/forms.html', context) def post(self, request): project_form = ProjectsForm(request.POST, request.FILES) p_formset = P_ImageForm(request.POST, request.FILES) # Checks if the form is valid before save #if p_formset.is_valid(): if project_form.is_valid() and p_formset.is_valid(): instance = project_form.save(commit=False) instance.user = request.user instance.save() images = p_formset.save(commit=False) images.save() data = { 'is_valid': True, 'name': images.p_file.name, 'url': images.p_file.url … -
django.contrib.auth.urls is no longer working after creating a Custom User model
I created a Custom user model from AbstractUserModel. I'm using django.contrib.auth.urls for simple login and logout functionalities including password_reset and When i'm still using the default user model of django, but its no longer working on my Custom user model. Is there a way to make this work for custom user model. (1146, "Table 'db.auth_user' doesn't exist") this is the error message i'm getting every time i login a sample account to my application. Thanks -
Compare urls in Django Template
In a django template I don't want to show some element in case if the url/path is a specific one. In pseudo: {% if not url = account:detail %} -
Django, I have added endif but it still shows an error?
my code <ul class="nav navbar-nav navbar-right"> {% if user.is_authenticated %} <li> <a href="#">Post</a> </li> <li> <a href="#">Groups</a> </li> <li> <a href="#">Create Group</a> </li> <li> <a href="{% url 'accounts:logout' %}">Log Out</a> </li> {% else %} <li> <a href="#">Groups</a> </li> <li> <a href="{% url 'accounts:login' %}">Log In</a> </li> <li> <a href="{% url 'accounts:signup' %}">Sign Up</a> </li> {& endif %} error shown is Unclosed tag on line 30: 'if'. Looking for one of: endif. -
'>' greater than sign has red color unlike '<' less than sign in vscode
enter image description here The image shows that the ">" greater_than sign has red color and when document is formatted it goes to next line as an open bootstrap tag -
how to save the particular django model filed as encrypted to database?
i have a user model in django models, password is one of the field in users table.While posting users the password should be saved to database as encrypted. iam using django restframework to post the users. -
How to limit the sample in the admin panel
I have a models class Section(CommonFields): class Meta: verbose_name = u'Раздел' verbose_name_plural = u'Разделы' leaf = False top_content = HTMLField(verbose_name=u'Блок контента сверху', blank=True, null=True) bottom_content = HTMLField(verbose_name=u'Блок контента снизу', blank=True, null=True) def get_min_price(self): items_ids = self.tree.get().children.values_list('object_id', flat=True) return Item.objects.filter(id__in=items_ids, show=True).aggregate(Min('price'))['price__min'] class Item(CommonFields): class Meta: verbose_name = u'Товар' verbose_name_plural = u'Товары' leaf = True price = models.PositiveIntegerField(verbose_name=u'Цена', blank=True, null=True) old_price = models.PositiveIntegerField(verbose_name=u'Старая цена', blank=True, null=True) sale = models.BooleanField(verbose_name=u'Скидка', default=False) hit = models.BooleanField(verbose_name=u'Хит продаж', default=False) property = HTMLField(verbose_name=u'Характеристики', blank=True, null=True) content = HTMLField(verbose_name=u'Контент', blank=True, null=True) feature = models.ManyToManyField('FeatureValue', verbose_name=u'Характеристики товара', related_name='items', blank=True) class Feature(models.Model): class Meta: verbose_name = u'Характреистика' verbose_name_plural = u'Характеристики' def __unicode__(self): return self.name name = models.CharField(max_length=255, verbose_name=u'Название') section = models.ForeignKey('Section', on_delete=models.CASCADE, verbose_name=u'Раздел', default=None) class FeatureValue(models.Model): class Meta: verbose_name = u'Значение характеристики' verbose_name_plural = u'Значения характеристик' def __unicode__(self): return self.value value = models.CharField(max_length=255, verbose_name=u'Значение') feature = models.ForeignKey('Feature', verbose_name=u'Характеристика', default=None) I want to see in the field of characteristics only those characteristics in which the section with the goods section coincides. I m use formfield_for_manytomany to filtering objects But its no working/ I m read offical documentation to Django 1.7.7 In admin.py class ItemAdmin(CatalogItemBaseAdmin): model = Item prepopulated_fields = {'slug': ('name',)} def get_form(self, request, obj=None, **kwargs): kwargs['formfield_callback'] = partial(self.formfield_for_dbfield, request=request, obj=obj) … -
Method Not Allowed(POST)
So I have been trying to implement a way to upload multiple files at once using JQuery for the client-side choosing part. I For some reason it is not working and I am not sure why. Nothing happens to my page and my terminal outputs "MEthod not allowed(POST): /create/" whenever I add images for the project I want to create. My code for this is below: basic-upload.js $(function () { /* 1. OPEN THE FILE EXPLORER WINDOW */ $(".js-upload-photos").click(function () { $("#fileupload").click(); }); /* 2. INITIALIZE THE FILE UPLOAD COMPONENT */ $("#fileupload").fileupload({ dataType: 'json', done: function (e, data) { /* 3. PROCESS THE RESPONSE FROM THE SERVER */ if (data.result.is_valid) { $("#gallery tbody").prepend( "<tr><td><a href='" + data.result.url + "'>" + data.result.name + "</a></td></tr>" ) } } }); }); views.py from django.shortcuts import render, redirect, reverse,get_object_or_404 from django.utils import timezone from django.core.files.base import ContentFile from django.forms import modelformset_factory from django.http import JsonResponse from django.views.decorators.http import require_http_methods from .models import Projects, P_Images from .forms import ProjectsForm, P_ImageForm # Create your views here. # Function to create projects @require_http_methods(["GET"]) def get_create_form(request): context = { 'project_form': ProjectsForm(), 'p_formset': P_ImageForm(), } return render(request, 'projects/forms.html', context) @require_http_methods(["POST"]) def create_projects(request): # Special case if the request method … -
Using URLS in Django 2.0
I am learning to create REST API with Django and for demo purposes I tried to replicate and use the tutorial given here.. I have created the project structure exactly as given in the tutorial. The current directory structure is as follows: cv_api cv_api __init__.py __pycache__ settings.py urls.py wssgi.py face_detector admin.py apps.py __init__.py migrations models.py tests.py views.py db_sqlite3 manage.py I have included the codes for face detection inside cv_api/cv_api/face_detector/views.py. I tried to edit cv_api/cv_api/urls.py to include the face_detector detect function as given in the tutorial. The following is what suggested in the tutorial: from django.conf.urls import patterns, include, url from django.contrib import admin urlpatterns = patterns('', # Examples: url(r'^face_detection/detect/$', 'face_detector.views.detect'), # url(r'^$', 'cv_api.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), ) However, since i am using django 2.0.6 i realised that the patterns function is deprecated. Hence, I tried to use the following: from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('detect/',face_detector.views.detect), ] But I am getting face_detector not found error when I run the manage.py runserver -
Celery task executing infinitely
I have implemented celery with django. I have created a task but after successful execution of my task it is not stopping. It is executing infinitely. Please suggest how to stop the task after successful execution. -
Unit test in Django Views
I am working on a Django Project I have a lot of views I need to test, but don't know how, this is one View, 'The login' view def iniciar_sesion(request): """Inicia sesión en la app web del Administrador""" template = loader.get_template('cenecu_admin/page_login.html/') if(request.method == 'POST'): usuario = request.POST.get('usuario') clave = request.POST.get('password') user = authenticate(username = usuario, password = clave) if (user is not None): login(request, user) iduser = request.user.id usuario_rol = UsuarioRol.objects.get(usuario_id = iduser) if(usuario_rol.rol == "admin" or usuario_rol.rol == "administrador"): messages.success(request, '¡Bienvenido!') return redirect('/') else: messages.success(request, 'Acceso no autotizado') return redirect ('/login') else: messages.success(request, 'Usuario y/o contraseña no válidos') return redirect ('/login') else: notice = 'none' context = { 'notice': notice } return HttpResponse(template.render(context, request)) How can I implement a unit test in test.py file? To validate this code -
How to use the serializer in part
I have several viewsets, several endpoints in them use one serializer. One endpoint does not even have a Meta class, It performs a certain action and uses the same serializer in the method to_representation. In this serializer I use the methodfield like this: some_field = serializers.SerializerMethodField() def get_some_field(self, obj): return bool(obj.something_attr) something_attr I get in viewset in queryset =MyModel.objects.annotate(something_attr=(...)) In others viewsets there is no such field, so they use other queriesets. Can I work around this problem without creating a bunch of additional serializers. My thanks! -
How do i import a pre-existing Django project into Eclipse?
Currently, there is no option in eclipse to import a Django project even after installing PyDev in eclipse. -
Redis is thread safe , so why use `BlockingConnectionPool` in redis-py
I use Django cache.I know Redis is thead-safe. If BlockingConnectionPool is necessary, when I configure CACHE. What does BlockingConnectionPool do? When I need use BlockingConnectionPool?