Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add count objects in Django Rest Framework Viewset
I have a question with adding Count Objects in Django Rest Framework Viewset: This is my curren API: [ { "id": 1, "created": "2017-12-25T10:29:13.055000Z" }, { "id": 2, "created": "2017-12-25T10:29:13.055000Z" } ] Now I want to add Count Objects outside this API and collect them in results array like this: { "count_objects": 2, "results": [ { "id": 1, "created": "2017-12-25T10:29:13.055000Z" }, { "id": 2, "created": "2017-12-25T10:29:13.055000Z" } ] } How can I do this in the right way? Now my viewset.py is: class NotificationAPIView(ReadOnlyModelViewSet): queryset = Notification.objects.all() serializer_class = NotificationSerializer def get_queryset(self, *args, **kwargs): queryset_list = Notification.objects.filter(to_user=self.request.user) return queryset_list -
How to run celery and redis i n django application
Hi I have a problem with a django application that executes stored procedures (oracle database) through celery tasks and redis. The application was running in a linux server but this fall down and then i lift the aplication up using python manage.py runserver but i don't know how to deal with the part that celery uses to run the tasks that call the stored procedures. here a view @csrf_exempt @login_required(login_url='/login/') def DynamicView(request): idc = request.GET.get('idc') idpl = request.GET.get('idpl') if request.method == 'POST': usuario = request.user rpost = request.POST form = DynamicForm(idpl,idc, request.POST) idc= request.POST.get('idcontrol') idpl= request.POST.get('idpl') if form.is_valid(): pl_ejecutar = BuildPl(idpl,idc,usuario,rpost) mensaje = pl_ejecutar dynamicExec.delay(pl_ejecutar,idc,idpl) nom_control = BuscarControl(idc) nom_pl = BuscarControlPl(idpl) usu = User.objects.get(username=usuario) nombre_usu = usu.username accion = 'Se ha ejecutado el Pl: ' \ + nom_pl + '. Para el Control: ' \ + nom_control + '. Por: ' + nombre_usu RegistroAcciones(usuario,accion) return HttpResponseRedirect('/monitor/') here a task @task(queue='ds') def dynamicExec(pl,pidc,pidpl): runpl = EjecutarPl() spe = runpl.ejecuta(pl,pidc,pidpl) return none here the model that call de store procedure class EjecutarPl(): def ejecuta(self, plv,idcv,idplv): cursor = connection.cursor() query = "begin cbs_django.ejecutar_pl_v2(:ppl,:pidc,:pidpl); end; " param = {"ppl":plv,"pidc":idcv,"pidpl":idplv} spexec = cursor.execute(query,param) cursor.close() return spexec i don't have experience using celery and redis so … -
accounts is not a registered namespace
in this django tutorial, we are creating a blogsite, at this pont we are creating a login form for users, unfortunately im getting and error saying that "accounts" is not a registered namespace, how do i fix this? my urls.py file for the app "accounts": from django.conf.urls import url from.import views appname= 'accounts' urlpatterns=[ url(r'^signup/$', views.signup_view, name= "signup"), url(r'^login/$', views.login_view, name = "login" ), ] my views.py for the app: from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm, AuthenticationForm def signup_view(request): if request.method== 'POST': form= UserCreationForm(request.POST) if form.is_valid(): form.save() #log the user in return redirect('narticle:list') else: form=UserCreationForm() return render (request,'accounts/accounts_signup.html', {'form': form}) def login_view(request): if request.method == "POST": form = AuthenticationForm(data= request.POST) if form.is_valid(): return redirect('narticle:list') else: form = AuthenticationForm() return render(request, 'accounts/login.html',{'form': form}) my base layout is: {% load static from staticfiles %} <!DOCTYPE html> <html> <head> <title>Narticle</title> <link rel="stylesheet" href="{%static 'styles.css'%}"> </head> <body> <div class="wrapper"> <h1> <a href="{% url 'narticle:list' %}">narticle </a> </h1> {% block content %} {% endblock %} </div> </body> </html> the template for login is: {% extends 'base_layout.html'%} {%block content%} <h1> log in</h1> <form class="site-form" action="{% url 'accounts:login' %}" method="post"> {% csrf_token %} {{form}} <input type="submit" name="log_in" value="login"> </form> {% endblock %} these are … -
What type of JSON data does DRF want?
I am using Vuejs and Django for my web app. Vuejs is responsible for sending all requests (GET, POST, PATCH, DELETE) through axios. submitContact() { const { first_name, last_name, email, hp_no, twitter, github, company } = this axios.post(this.apiUrl, { first_name, last_name, email, hp_no, twitter, github, company, }) .then() .catch((err) => { console.log(err) }); This function is called when the form is submitted. For handling POST data in views: def contact_data(request): if request.user.is_authenticated(): # When user is authenticated if request.method == 'GET': # For viewing records contacts = Contact.objects.all().filter(user=request.user.id) contacts_serialized = ContactSerializer(contacts, many=True) return JsonResponse(contacts_serialized.data, safe=False,) elif request.method == 'POST': # For creating a record json_data = json.loads(request.body) print(json_data) serializer = ContactSerializer(data=json_data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=status.HTTP_201_CREATED) return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': # For deleting a record pass else: # When user is not authenticated return HttpResponse("You are not authorized to access!") Currently, When I am making a form submission, the view is getting a JSON POST Response like this: {'first_name': 'Jane', 'last_name': 'Doe', 'email': 'jane@gmail.com', 'hp_no': '0111634859', 'twitter': 'jane93', 'github': 'jane23', 'company': 'Jane ltd'} But the serializer is taking it as an invalid serialized data and returning an 400 response. What might be the step I am … -
Automatically set the value of next in all django CBV
I want my website to work like this: Attempt to go to a URL. (=>should become the 'next' parameter) You get redirected to the login page, because you're not logged in. After logging in, it should take you to 'next.' Nobody has ever framed their usage of next in this manner, so far that I've seen on S.O. and the docs don't help at all. Everyone else asks how to redirect if you click Login explicitly. Do I have to modify every single get_success_url() or get_context_data() method in every one of my CBV to properly give it the 'next' parameter? I can't even tell which view is actually saying "oh you're not logged in, go to /login/ ," cause if I could tell that I could at least attempt to override that method and give it the request.path parameter. I assume it is AuthenticationMiddleware, or LoginRequiredMiddleware Apparently it isn't "LoginView" (django 1.11) because when I put a breakpoint on the dispatch method there, it doesn't see my original attempted URL anywhere, it simply sees request.path = '/login/' How do I nab the value of "originally intended url" and set it to the 'next' parameter, so that it redirects to '/login/?next=next_page' … -
Loop through the end of a Django queryset
I am trying to loop through a Django queryset, starting at the last record and going back 1,000 records at a time. I'm able to get the last 1,000 records with the following query: employees = Employee.objects.all().order_by('-id')[:1000] Say my queryset is 10,0000 results. How can I go from 8,000 to 9,000? Do I have to use .count() to get the total record count? My full queryset is 12 million records so I am trying to avoid that if possible. -
Best place to update related fields via django-import-export
In our project, we have to import and export complicated models in *.xls and other formats. django-import-export great tool and helped us. I wrote a lot of code for creating/editing related models vie additional meta fields (two or three levels in deep). I used import_row, import_field, before_import_row and others methods in our base ModelResource. And now I have little trouble where to place the code for simple logic. We want to update related object's field. For example: class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): author = models.OneToOneField(Author) I want to export and import (update) author__name via book resource. I tried to write Widget for this field but it wasn't a good idea. Give me an example how to export end import author__name from BookResource in right way, please. -
Django - disallow NaN and infinity in FloatField
How can I make a FloatField in Django that does not allow saving NaN or Infinity values (while still allowing null values) - i.e. something along the lines of: class MyModel(models.Model): rate = models.FloatField(null=True, nans=False) # ??? I am using Postgres as a backend. If a general solution does not exist, maybe there is a Postgres specific solution? -
Django: All URLs are getting redirected to 404
Following is my urls.py file: from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static handler400 = 'mysite.views.bad_request' handler403 = 'mysite.views.permission_denied' handler404 = 'mysite.views.page_not_found' handler500 = 'mysite.views.server_error' urlpatterns = [ url(r'^', include('app1.urls')), url(r'^', include('app2.urls')), url(r'^', include('app3.urls')), url(r'^admin/', admin.site.urls), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) This started when I have recently uploaded the application to Digital ocean on Ubutu box which is serving pages using Apache2 and mod_wsgi. Site is being redirected to the custom 404 HTML template which I have created. What can be the reason, please suggest. -
Debug Django code in Docker
I want to debug my Django code running through docker container. Is it possible with PDB, PYCHARM debugger or with another technique? -
django-bower: `./manage.py bower install` (and variants) fail with KeyError: 'bower'
New to Django. I'm trying to clone and set up a pre-existing Django project which uses django-bower. It uses Django 1.10.6 and django-bower 5.2.0. I've set up a new virtualenv with all the project's requirements. The manage.py file is the same as the example from the django-bower library: #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "example.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) Running ./manage.py bower install (bower_install) too fails because Django and django-bower are only installed in the virtual environment. When I run it through python manage.py bower install or python manage.py bower_install I get this stack trace: Traceback (most recent call last): File "/usr/lib/python3.5/site-packages/django/core/management/__init__.py", line 189, in fetch_command app_name = commands[subcommand] KeyError: 'bower' -
How can I run function asynchronously to make calculation parallelly on Heroku with Django app?
I have to run function 500 times with different arguments on Heroku with hobby plan in my Django app at a specific time. I need to do it in the shortest period of time. I noticed that when I use Heroku Scheduler every task is running parallelly and asynchronously and each of them has own worker. So for example 10 functions ran in this way will calculate results as there would be only 1 ran function. As I have mentioned I need to run 500 functions with different arguments. I could create 500 Heroku schedulers and ran it separately but it seems to me that it's not supported by Heroku or maybe I am wrong? If so maybe someone know how it could be solved in another way? -
I can't change main Django project settings file
I was trying to configure the Django Database Settings to use mysql. I followed the instructions provided here I started a Django project within the myproject directory. django-admin.py startproject myproject . I tried to open the main Django project settings file nano ~/myproject/myproject/settings.py And the terminal did not display a DATABASES section at the bottom of this file. Instead I had ^G Get Help ^O WriteOut ^R Read File ^Y Prev Page ^K Cut Text ^C Cur Pos ^X Exit ^J Justify ^W Where Is ^V Next Page ^U UnCut Text^T To Spell What do you recommend? I need to change this settings file to use mysql database.I have Ubuntu 14.04. and python 3.4. installed. -
Django - Getting AttributeError 'User' object has no attribute 'cleaned_data' while cleaning form data
I was trying to make a user registration page in Django. everything went fine. but when I submit the form data I get this below error AttributeError 'User' object has no attribute 'cleaned_data' Image of that AttributeError I searched on stackoverflow and found that the object.cleanded_data should be placed after object.is_valid() else one should face the AttributeError. But I placed that after checking is_valid() still getting error. my codes: views.py class UserFormView(View): form_class = UserForm template_name = "music/registration_form.html" def get(self, request): form = self.form_class(None) return render(request, self.template_name, {"form": form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) username = user.cleaned_data["username"] password = user.cleaned_data["password"] user.set_password(password) user.username = username user.save() user = authenticate(username= username, password= password) if user is not None: if user.is_active: login(request, user) return redirect("music:index") return render(request, self.template_name, {"form": form}) forms.py from django.contrib.auth.models import User from django import forms class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ["username", "email", "password"] I cant find where I made mistake. -
Adding fields to table dynamically in django
After reading about database designs, i've decided to go with a single table for all users. my question is how can i create fields for new users to add their data into it? also what's a good approach for retrieving data specific to each user? I appreciate any advise regarding this subject. -
can not connect module django-AB-project
I installed the library itself, added in INSTALLED_APPS = [ 'ab' ] But for some reason I get an error if I'm making a migration: ModuleNotFoundError: No module named 'ab' I use django==1.11 -
How can I calculate time from model object created time?
models.py @python_2_unicode_compatible class UserAuthToken(models.Model): email = models.ForeignKey(UserSubEmail) token = models.CharField(max_length=34, unique=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return "AuthToken for %s" % self.email I want to check elapsed time between token's created time and now So if token created before more than 10 minutes, I can recognize this token is invalid. views.py def create_email_confirm_key(request, uid, token): try: user_authtoken = UserAuthToken.objects.get(uid=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user_authtoken = None if not 'user_authtoken is created before more than 10minutes' : This token is valid and do something How can I calculate and check time between the token created and now? -
Send Python Data on Django
I have informations generated by a Python Script and I'd like to recovering this datas on Django. Simplifying: Python Script: extract information from log system Django: Web View - Is how I would like to show this informations to my user. Does Django has any features to it that or I need to create a webservice, because, one I am not familiarized with this Framework, I would send this data on to PHP using WEBService. -
Django SQL query duplicated 2 times
Model.py: class Match(models.Model): home_team = models.CharField(max_length=200) away_team = models.CharField(max_length=200) class Stat(models.Model): match = models.ForeignKey(Match) team = models.CharField(max_length=100) goals = models.IntegerField(default=0) assists = models.IntegerField(default=0) views.py context_dict = {} match = Match.objects.get(pk=1) home_stat = Stat.objects.get(match=match, team=match.home_team) away_stat = Stat.objects.get(match=match, team=match.away_team) context_dict['home_stat'] = home_stat context_dict['away_stat'] = away_stat return render(request, 'index.html', context_dict) template goals: {{ home_stat.goals }} : {{ away_stat.goals }} assists: {{ home_stat.assists }} : {{ away_stat.assists }} django-debug-toolbar shows two duplicated queries: https://sfault-image.b0.upaiyun.com/220/984/2209840587-5a3e5ccccec87_articlex SELECT "myapp_stat"."id", "myapp_stat"."match_id", "myapp_stat"."team", "myapp_stat"."goals", "myapp_stat"."assists" FROM "myapp_stat" WHERE ("myapp_stat"."match_id" = '1' AND "myapp_stat"."team" = '''TeamA''') Duplicated 2 times. F:\myproject\myapp/views.py in index(11) home_stat = Stat.objects.get(match=match, team=match.home_team) SELECT "myapp_stat"."id", "myapp_stat"."match_id", "myapp_stat"."team", "myapp_stat"."goals", "myapp_stat"."assists" FROM "myapp_stat" WHERE ("myapp_stat"."match_id" = '1' AND "myapp_stat"."team" = '''TeamB''') Duplicated 2 times. F:\myproject\myapp/views.py in index(12) away_stat = Stat.objects.get(match=match, team=match.away_team) how to fix this? -
Django RegexValidator pattern for ZZ-99-ZZ-9999
Trying to make a regex pattern in pattern ZZ-99-ZZ-9999 (2 capital character-2 numbers-2 capital character-4 numbers) bus_number_regex = RegexValidator(regex=r'^\W{2}-?1?\d{2}-?1?\W{2}-?1?\d{4}$',message="Bus number must be entered in the format: 'ZZ-99-ZZ-9999'"." ZZ must be in Capital.") -
How can I run function asynchronously to make calculation parallelly on Heroku with Django app?
I have to run function 500 times with different arguments on Heroku in my Django app at a specific time. I need to do it in the shortest period of time. I noticed that when I use Heroku Scheduler every task is running parallelly and asynchronously and each of them has own worker. So for example 10 functions ran in this way will calculate results as there would be only 1 ran function. As I have mentioned I need to run 500 function with different arguments. I could create 500 Heroku schedulers and ran it separately but it seems to me that it's not supported by Heroku or maybe I am wrong? If so maybe someone know how it could be solved in another way? -
cant deploy django to ehost shared cpanel
i have a hosting package on ehost.com and i am trying to deploy a django application on it and i am having many problems first was that the django version i used is 2 and the pip version on ehost servers is with python 2.7 which is not compatible with django 2 then when trying to deploy a django 1.11 app which is compatible with python2.7 i followed all the instructions in the ehost django with fast cgi guide and the server doesnt execute the index.fcgi file it just returns the text in the file and the website support concerning these issues are not really helping -
Django ORM - Filter by GenericRelation across multiple models
Filtering on Django GenericRelations has been implemented 4 years ago via https://code.djangoproject.com/ticket/22207 and supports now to filter from the related model: class Issue(models.Model): project_content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, blank=False, null=True) project_id = models.PositiveIntegerField(blank=False, null=True) project = GenericForeignKey('project_content_type', 'project_id') class GitlabProject(models.Model): issues = GenericRelation( Issue, related_query_name='generic_project', content_type_field='project_content_type', object_id_field='project_id', ) and then: issues = queryset.filter(generic_project__offers__members__in=[request.user]) We cannot use just project__offers_members - it would fail, as Django does not reversely resolve Generic Foreign Keys. However what happens if we have another project model with the same related_query_name? class JiraProject(models.Model): issues = GenericRelation( Issue, related_query_name='generic_project', content_type_field='project_content_type', object_id_field='project_id', ) I have tried setting the GenericRelation with the same related_query_name on all the different project models (i.e. Gitlab Project, Jira Project, etc.). However that results in Django picking up only the 'first' project model. The generic relation to all subsequent project models are ignored and as a result, issues that have instances set that do not belong to the 'first' project model are ignored and not part of the queryset. I think Django should either support this or issue a warning or error (possibly when executing the makemigrations command), when multiple GenericRelations have the same related_query_name value set. How can one filter efficiently across issues that have … -
Temporary views are not supported in CouchDB
I'm building a web app using Django and couchdb 2.0. The new version of couchdb doesn't support Temporary views. They recommend using Mongo query but I couldn't find any useful documentation. What is the best approach or library to use couchdb 2.0 with Django? -
Access via ForeignKey to the image field of parrent model in QuerrySet [Django]
I have this simplified model.py: class Product(models.Model): name = models.CharField() description = models.CharField() class ProductImage(models.Model): product = models.ForeignKey(Product,) photo = models.ImageField(upload_to="product_images/") is_main = models.BooleanField(default=False) An Product can have many ProductImage, but only ProductImage which has field is_main=True shall be rendered in a template together with all field of Product. The following data set from the views.py: products = Product.objects.all() So now I would want to do something like this in the template: {% for product in products %} <img class="card-img-top" src="{{ product.productimage_set.filter(is_main=True).photo }}" alt="Card image cap"> <div class="card-body"> <h4 class="card-title">{{ product.name }}</h4> <p class="card-text">{{ product.description }}</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> But obviously that's not possible. Not from the template directly, at least. What is the proper way to get all the fields of Product and its image with attribute is_main=True inside the template?