Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django urls -Reverse for 'url name' not found
I have a Django application called polls. I'm trying to use a form in a template that it's action is calling to another url. mysite/urls.py: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^$', include('polls.urls')), url(r'^admin/', admin.site.urls), ] polls/urls.py: from django.conf.urls import url from . import views app_name = 'polls' urlpatterns = [ url(r'^$', views.call_login, name='call_login'), url(r'^homepage/$', views.login, name='login'), ] login.html: <form name="form" method="post" action="{% url 'login' %}" > {% csrf_token %} <input type="text" placeholder="username" name="user"><br> <input type="password" placeholder="password" name="password"><br> <input type="submit" value="Login" /> </form> The error I got: NoReverseMatch: Reverse for 'login' not found. 'login' is not a valid view function or pattern name. Any idea why? -
One view fo multiple urls to handle multiple languages in django
I would like to use the same views for different supported languages. For exemple I have the default language and the english. In my main urls: url(r'^posts/', include('posts.urls')), #for default language url(r'^en/posts/', include('posts.urls')), #for english The urls file of my posts app is like this: url(r'^newpost/$', views.PostFormView.as_view(), name='add'), url(r'^favorite/$', views.favorite, name='favorite'), so, for example, both www.mysite.com/posts/add and www.mysite.com/en/posts/add send to the same view PostFormView and according to the url if it contains "/en/" or not I send the content in the right language. However, the issue is with the redirect or revers sends always to the default language. For example 'posts:add' sends always to "www.mysite.com/posts/add" because I have url(r'^posts/', include('posts.urls')) before url(r'^en/posts/', include('posts.urls')) are there any ways to use the same view for two different urls. Or, how can I handle multiple languages website? Do we have to duplicate all the apps for all the supported languages? -
Django- Paypal integration issue
Django - Paypal integration issue on credit card checkout... How do I make auto-fill credit card details in new express checkout for PayPal payments. I have to integrate it with Django Donate App. Please don't suggest this :- https://developer.paypal.com/docs/classic/express-checkout/integration-guide/ECCustomizing/#automatically-fill-out-shipping-and-contact-information. This was deprecated from January. -
Django rest framework custom return response
So i have this custom register api which register a user, but when user successfully register, i want it to have this message "You have successfully register an account!" But i tried different method but get an error instead. serializer.py class UserCreate2Serializer(ModelSerializer): email = EmailField(label='Email Address') valid_time_formats = ['%H:%M', '%I:%M%p', '%I:%M %p'] birthTime = serializers.TimeField(format='%I:%M %p', input_formats=valid_time_formats, allow_null=True, required=False) class Meta: model = MyUser fields = ['username', 'password', 'email', 'first_name', 'last_name', 'gender', 'nric', 'birthday', 'birthTime'] extra_kwargs = {"password": {"write_only": True}} def validate(self, data): # to validate if the user have been used email = data['email'] user_queryset = MyUser.objects.filter(email=email) if user_queryset.exists(): raise ValidationError("This user has already registered.") return data def create(self, validated_data): username = validated_data['username'] password = validated_data['password'] email = validated_data['email'] first_name = validated_data['first_name'] last_name = validated_data['last_name'] gender = validated_data['gender'] nric = validated_data['nric'] birthday = validated_data['birthday'] birthTime = validated_data['birthTime'] user_obj = MyUser( username = username, email = email, first_name = first_name, last_name = last_name, gender = gender, nric = nric, birthday = birthday, birthTime = birthTime, ) user_obj.set_password(password) user_obj.save() return validated views.py class CreateUser2View(CreateAPIView): permission_classes = [AllowAny] serializer_class = UserCreate2Serializer queryset = MyUser.objects.all() i tried changing this into the serializer user_obj.set_password(password) user_obj.save() content = {'Message' : 'You have successfully register an … -
PrimaryKeyRelatedField(source='order.market', read_only=True) gives an AttributeError
models.py class ClientTransaction(model.Models): order = models.ForeignKey('main.Order', related_name='client_transaction', on_delete=models.PROTECT, null=True) class Order(BaseModel): market = models.ForeignKey('main.Market', on_delete=models.PROTECT, related_name='order') serializers.py class ClientTransactionSerializer(ModelSerializer): market = serializers.PrimaryKeyRelatedField(source='order.market', read_only=True) class Meta: model = ClientTransaction fields=['market'] Giving an error: AttributeError: 'NoneType' object has no attribute 'market' django==2, djangorestframework=>3.7.1 full error image -
how to apply a condition to a queryset in django
I am new to programming, I have a doubt I formed the QuerySet with table data i want to know how to apply condition to the formed queryset and get the count. Code : final_set = TaskMaster.objects.filter(istaskactive=True) I want something like no_of_rebuild_task = final_set..objects.filter(tasktype.id=1).count model.py class TaskMaster(models.Model): sid = models.CharField(max_length=3) # Remember to change the default value in processor in production processor = models.ForeignKey(User,null=True,on_delete=models.CASCADE,default=1) tasktype = models.ForeignKey(TaskTypeTable, null=True,on_delete=models.CASCADE) task_title = models.TextField(null=True) task_description = models.TextField(null=True) datacenter = models.ForeignKey(DatacenterTable,null=True,on_delete=models.CASCADE) priority = models.ForeignKey(PriorityTable, null=True,on_delete=models.CASCADE) status = models.ForeignKey(StatusTable, default=1,on_delete=models.CASCADE) pid = models.IntegerField(null=True) sourceincident = models.CharField(max_length=250,null=True) errorincident = models.CharField(max_length=250,null=True) processingteam = models.ForeignKey(TeamTable,null=True,on_delete=models.CASCADE) createddate = models.DateField(("Date"), default=datetime.date.today) duedate = models.DateField(("Date"), default=datetime.date.today) istaskactive = models.BooleanField(default=True) -
How the duplication of data come in django and how can I avoid it?
I am doing a project by django,just a person project. I try the project by django with celery,and add two task in celery. one task, is about a spider write by requests,get some proxy ip information and save to mysql by django orm ,which is update_or_create(defaults={'ip':'','port':''},**{'key':'value'}).I keep this task would always control data by one worker through redis lock.such as ,one work run the task,redis lock get and the other work try to get lock failed and would not contorl the data. the other task,is a spider,write by tornado,which is used to check the proxy ip data. Also, would run by one worker through redis lock. and the spider by tornado is a single thread ,too. the two task may run at the same time. Here comes the problem! when I run the project a few time later,about several hours later. I found some data are the same in mysql. The ip,port and some others are the same. And when the code run to update_or_create() comes the error : get() return 2. How the data come? In my thought,although at most two thread would run together, but one is use updata_or_create,one is use .save() .The task use save() would not … -
django custom model field example REF/001 then REF/002
i want to create custom field which i dont have any idea example response needed during createview REF/001 = which 1 is pk for first record REF/002 = which 2 is pk for second record Thanks for help -
Using converted strings for urls in django 2.0
I'm having trouble including strings for URLs in my django project. My models have a property called trig, which is a three character string (defined as CharField, max_length=3) urls.py in my module directory: #/nation/xxx/ path('nation/<str:trig>/', views.nation, name='nation'), URLs above and below this one work, but this one gives me TypeError. What I'm looking for in the end is being able to see a page that will give a different page for "http://url/nation/ENG/" as opposed to "http://url/nation/AUS/" I've tried (pardon spaces) < int:trig > (didn't work because integer) and < trig > (which also gives TypeError). Am I describing the path correctly? If not, what am I doing wrong? -
How to categorize objects associated with ForeignKey Django
I have two model classes class Category(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name and class Site(models.Model): name = models.CharField(max_length=200) category = models.ForeignKey('Category', on_delete=models.SET_NULL, null=True) link = models.CharField(max_length=200) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) def __str__(self): return self.name So in the templates, I wanted to categorize (put together) sites with the same category together. As in there will be links with all categories on the home page {% for category in category_list %} <li><a href="">{{ category.name }}</a></li> {% endfor %} and when you click the link for a category, the sites with the same categories appear. How do I do that? -
Django REST Framework serializer - access existing foreign key
I am using Django Rest Framework in my app, and I need to create new model instances which contain foreign keys. These refer to existing objects in another table, so I don't want new instances of these foreign objects to be created. Also I cannot access these objects via their primary keys, as that information is not submitted (I need to filter on certain fields which are included in the POST request). How do I do this? This question seems to address the same issue, though it's not clear to me that the accepted answer actually solves the problem. Suppose I have two models, Category and Item, with a ForeignKey field in the latter specifying the category: class Category(models.Model): name = models.TextField() format = models.TextField() page = models.IntegerField(default=1) order = models.IntegerField(default=1) class Item(models.Model): username = models.TextField() title = models.TextField() category = models.ForeignKey('Category', null=True) data = JSONField(null=True, blank=True) The body of the POST request consists of a JSON payload, with the category defined as an object specifying the format, page and order fields: POST /api/items { "username" : "test", "title" : "foo", "category" : { "format" : "A", "page" : 2, "order" : 1 }, "data" : [1,2,3,4,5] } Then I … -
How to integrate many-to-one field into django form
I have three model classes like these: InstallationReportInstance has a many-to-one relationship to InstallationReportData. class InstallationReportData(FormData): installationDate = models.DateField(null=True, blank=False, verbose_name="Date of Installation") deliveryOrder = models.CharField(null=True, blank=True, max_length=255, verbose_name="Delivery Order") unitSerialNumber = models.CharField(null=True, blank=False, max_length=255, verbose_name="Unit S/N") unitHours = models.DecimalField(null=True, blank=False, decimal_places=2, max_digits=5, verbose_name="Unit Hours") visualInspection = models.BooleanField(default=False, verbose_name="Visual Inspection") ... class InstallationReportPartDefinition(models.Model): deviceType = models.CharField(max_length=3, choices=DeviceProfile.TYPE_DEVICE, default='E', verbose_name="Device Type") productCode = models.CharField(max_length=32, blank=False, null=False, unique=True, verbose_name="Product Code") itemDescription = models.CharField(max_length=1023, blank=False, null=False, verbose_name="Item Description") quantity = models.CharField(max_length=255, blank=False, null=False, verbose_name="Quantity") class InstallationReportPartInstance(models.Model): definition = models.ForeignKey(InstallationReportPartDefinition, on_delete=models.CASCADE, related_name="instances", verbose_name="Definitions") installationReport = models.ForeignKey(InstallationReportData, on_delete=models.CASCADE, related_name="parts", verbose_name="Installation Report") received = models.BooleanField(default=False, blank=True, verbose_name="Received") installed = models.BooleanField(default=False, blank=True, verbose_name="Installed") I have a form for InstallationReportData that should look like this: Other form fields... | Product Code | Description | Quantity | Received | Installed | | xxx1 | desc1 | 2 items | YES | NO | | xxx2 | desc2 | 1 set | NO | NO | | xxx3 | desc3 | 2 items | YES | NO | Or, in real: So, the view is like this: class InstallationReportView(BaseCreationView): model = InstallationReportData form_class = InstallationReportDataForm template_name = 'mism_web/forms/installation_report.html' permission_denied_message = "You do not have permission to fill installation report data." … -
how to make django channel comsumer to send reply asynchronously
in my consumer , I write serveral reply_channel.send > def ws_message(message): > line = get_output() > message.reply_channel.send({ > "text": line, > }) > line = get_output() > message.reply_channel.send({ > "text": line, > }) line = get_output() > message.reply_channel.send({ > "text": line, > }) And I found that the comsumer did not send these three replies unitl the last message.reply_channel.send is executed. What can I do to make it send reply immediately when each reply_channel.send is ececuted? I did this because I have a program generating output at a random interval . If I use the code above , the webpage will wait unitl the full result arrives and it's quite unfriendlly for users. Thanks! -
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?