Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django : Heroku App crashed" method=GET path="/robots.txt
My app works fine on localhost but whenever i push it to heroku it gives the error below and app crashes -
django project not recognizing apps even though in installed_apps
I just upgraded my project from django 1.8 to 2.0 and now my project isn't recognizing the apps, templates, template tags, or anything to do with my apps. Any ideas? -
Jinja2 filters for dynamic registered templates
I've got the following code: from app.utils.logic.template_filters import get_date_europe env = Environment( loader=FileSystemLoader(template_dirs), autoescape=True, extensions=['jinja2.ext.i18n'], ) env.install_null_translations() env.filters['get_date_europe'] = get_date_europe def render_from_text(text, **context): t = jinja2.Template(text) return t.render(**context) and I want to add a custom filter to perform specific datetime formatting. text is a valid template stored as string. The problem is that when line {{ some_object.created_at|get_date_europe }} is included into template, jinja throws an exception jinja2.exceptions.TemplateAssertionError: no filter named 'get_date_europe' I set a debug breakpoint into first line of render_from_text and called env.filters, function appears to be there 'get_date_europe': <function get_date_europe at 0x10fca02f0>,. How can I make my filter visible to jinja? P.S. Django 1.9 is used. -
Not able to retrieve selected values from Django's Choicefield Form
Following is my Django form class Country(forms.Form): name = forms.CharField() country = forms.ChoiceField(widget=forms.Select(attrs={'id':'country'})) Following is code before sending form to a HTML page form = Country() choices = [('a', 'India'), ('b', 'United States of America')] form.fields['country'].choices = choices form.fields['country'].initial = 'b' return render(request,"Test.html",{"form":form}) Form is rendered properly in the front end and initial value is also set. When user clicks submit button. It is throwing exception. Following is the code i have written when user clicks submit button, f = Country(request.POST) print (f) print("Country Selected: " + f.cleaned_data['country']) I am getting the form like below when i printed the form after user submitted. <tr><th><label for="id_name">Name:</label></th><td><input type="text" name="name" value="ggg" id="id_name" required /></td></tr> <tr><th><label for="country">Country:</label></th><td><ul class="errorlist"><li>Select a valid choice. a is not one of the available choices.</li></ul><select name="country" id="country"> </select></td></tr> Please help me with this. Thanks! -
Pass hidden input along with a form on a Bootstrap 3 modal
Goal: I have a button that toggles Bootstrap 3 modal. The modal has a Django form on it. I want to pass an id along with the form when it is submitted (so that I can query DB with the id and save the cleaned data into an according row). Problem: I have everything working except submitting an id with the form. My approach was to create a hidden input element on the modal, but (a) I'm not sure if it's a feasible way and (b) the way my code is now, input element isn't being added. Code: To get straight to the point, I'm omitting views.py. Just assume id and form below are Python variables passed to the templates. #button.html #bootstrap and jquery are included in the header <script src="http://malsup.github.com/jquery.form.js"></script> <button data-toggle="modal" class="btn btn-info btn-lg" href="/app/modal/" data-target="#modal{{ id }}">click</button> <div class="modal fade" id="modal{{ id }}"> <div class="modal-dialog modal-lg"> <div class="modal-content"> ... </div> After some research, I based my modal on this. #modal.html #nothing included in the header <div class="modal-dialog modal-lg"> <div class="modal-content"> <form id="form" method='post' action=''> <div class="modal-header"> ... </div> <div class="modal-body"> {% csrf_token %} {{ form.as_table }} </div> <div class="modal-footer"> <input type="submit" id="btn" value="submit"/> </div> </form> <script> document.getElementById(btn).onclick … -
how to connect to my localhost server to run a django application?
i'm studying Django and now can't connect to my localhost server to run my projects even when i'm trying to run the browser on my local IP. help please -
How to implement "Drag and Drop" functionality in django-mptt?
I use django-mptt application in my project. This application allows users drag and drop tree nodes in admin page (DraggableMPTTAdmin). Is it possible to make the same functionality in custom template (not in admin)? P.S. I tried to use jsTree plugin in frontend. This plugin allows the user drag and drop nodes of the tree but jsTree has heavy API. Also I dont know how to save new structure of new tree cause jsTree render strange attributes in html for tree nodes. template: <ul class="root"> {% recursetree nodes %} <li> {{ node.name }} {% if not node.is_leaf_node %} <ul class="children"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} </ul> -
django-ses setting error : Module "django_ses" does not define a "SESBackend" attribute/class
I'm trying to send email using django-ses library and Amazon ses. I did all essential settings following this(https://github.com/django-ses/django-ses, installing boto and django-ses, insult AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and EMAIL_BACKEND = 'django_ses.SESBackend' in my settings.py) but when I tried to send email. I've got an error. ImportError: Module "django_ses" does not define a "SESBackend" attribute/class Is there any bugs in this django-ses library, or am I doing wrong something? I'm using windows 10, python3, and django 1.11 -
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 …