Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to to run a python script using a button! (Using Django)?
I am a django newbie! I want to know how to run a python script on pressing a button using django! The script does return any value but it does some changes to a test account on a server(Google Ad Words Test Account). The script is ready! It would be really appreciated if someone could help me out! -
Change the template option based on the condition
How to change the template tag based on another template tag. task_count = {1 :3, 2: 0, 3: 1} --- i manually created task_type = {1:rebuild,2:upgrade,3:provisioning} ---- this from table I want to get the task count for ex: if the task id 1 then "Rebuild:3". I tried the below code it's not working {% for task in TaskTypeTag %} {{task_count.{{task.id}}}} -
add django csrf token to angular 5 form
im working on django-angular5 project i have a login form in angular how should i add csrf token to my form ? without what i get this error i searched same topic but people are using angular js that will not help me (i ng build angular app and im using static files) Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: CSRF token missing or incorrect. it is my simple form for login in home.compoenent.html <form method="post"> <div class="input-field col s6"> <input id="first_name" type="text" name="username" class="validate"> <label for="first_name">نام کاربری</label> </div> <div class="input-field col s6"> <input id="first_name" type="password" name="password" class="validate"> <label for="first_name">کلمه عبور</label> </div> <input type="submit" class="waves-effect waves-light btn" value="login"/> <input type="hidden" name="next" value="{{ next }}"/> </form> -
Django LDAP authentication to another webpage
My company has a single common LDAP server for every web based products. I am developing an Django web product called myapp, which load some data/iframe from another web product called another_app. When user log in to myapp , they also need to open a new tag and log in to another_app, in order to be able to view some graph data loaded from another_app. It bring a little inconvenience I dont have any information about how another_app implemented , except confirm that, both myapp and another_app use the aforementioned LDAP server for their authentication. So question is: Any mechanism allow whenever user login to myapp, they also login to another_app . As mentioned , I developing myapp using Django/LDAP. Thanks -
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!