Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to run python script in html using django and get variable from html input form
i have a sentiment analysis python script, but I want to make it runs in html and get the input form from html page, and the shows the result back in html page. I already use a django framework to run html page. But i don't know how to connect it with python script I have. this is my python script query = input("query? \n") number = input("number of tweets? \n") results = api.search( lang="en", q=query + " -rt", count=number, result_type="recent" ) print("--- Gathered Tweets \n") ## open a csv file to store the Tweets and their sentiment file_name = 'Sentiment_Analysis_of_{}_Tweets_About_{}.csv'.format(number, query) with open(file_name, 'w', newline='') as csvfile: csv_writer = csv.DictWriter( f=csvfile, fieldnames=["Tweet", "Sentiment"] ) csv_writer.writeheader() print("--- Opened a CSV file to store the results of your sentiment analysis... \n") ## tidy up the Tweets and send each to the AYLIEN Text API for c, result in enumerate(results, start=1): tweet = result.text tidy_tweet = tweet.strip().encode('ascii', 'ignore') if len(tweet) == 0: print('Empty Tweet') continue response = client.Sentiment({'text': tidy_tweet}) csv_writer.writerow({ 'Tweet': response['text'], 'Sentiment': response['polarity'] }) print("Analyzed Tweet {}".format(c)) ## count the data in the Sentiment column of the CSV file with open(file_name, 'r') as data: counter = Counter() for row in csv.DictReader(data): … -
How to process a Celery task on a specific vhost?
I have a Celery task like: from celery.task import task from django.conf import settings @task(name="throw_exception") def print_value(*args, **kwargs): print('BROKER_URL:', settings.BROKER_URL) and I'm running a Celery worker inside my virtualenv like: celery worker -A myproject -l info The Worker shows: Connected to amqp://guest:**@127.0.0.1:5672/myapp And when I launch my task from the Django shell with: >>> from django.conf import settings >>> settings.BROKER_URL 'amqp://guest:**@127.0.0.1:5672/myapp' >>> from myapp.tasks import print_value >>> print_value.delay() I never see the task executed in my worker's log. However, if I instead change my worker to use a BROKER_URL with the default "/" vhost, then it immediately executes all the pending tasks, implying all my calls of print_value.delay() are sending it to the wrong vhost even though the correct BROKER_URL is set. What am I doing wrong? -
Celery ignoring vhost in BROKER_URL
I have several separate Celery workers each processing events from a unique RabbitMQ vhost. In my Django settings, I print out the BROKER_URL in the Celery log, which looks like: amqp://guest:guest@127.0.0.1:5672/myname However, immediately under that line in the log is Celery's initialization message: [2017-11-01 00:18:16,568: INFO/MainProcess] Connected to amqp://guest:**@127.0.0.1:5672// which shows no vhost. I have a sample event that sends an email. If I launch this for a specific vhost, it gets executed by a random Celery worker, instead of the Celery worker for the correct vhost. Why is Celery seemingly ignoring the BROKER_URL and my custom vhost? I setup my Django+Celery settings according to the docs, and it works perfectly when I run a single Celery worker on localhost. -
Django REST Generic View for related model
I have a setup similar to this - a Cookbook class, which has multiple Recipes. I have a class CookbookListCreateView(ListCreateAPIView): permission_classes = (IsAuthenticated,) queryset = Cookbook.objects.all() serializer_class = CookbookSerializer and this handles creating / listing the cookbooks. I need a ListCreateView for the Recipe model but the list must belong to a specific cookbook, in such a way that this url: /cookbook/2/recipes would return only recipes found in a cookbook with pk of 2. How can I modify ListCreateAPIView to follow this behavior? -
Storing image in a local file system without model in Django?
I'm a beginner in Django. I'mworking with Rest Api framework for creating a small image mangement api with just "get" and "post" methods. The problem i'm facing is i don't want to save the reference of images in my model instead i just want to save it in my local media folder without any image metadata in my model. So, is there any module to work around this and save it in my local file system after serializing every image that is sent using POST? -
django-auth-ldap installation not working
I am trying to install django-auth-ldap in my windows system it shows the following error \pip-build-3x6rkxb4\pyldap\modules\errors.h(8): fatal error C1083: Cannot open include file: 'lber.h': No such file or directory error: command 'C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\cl.exe' failed with exit status 2 My versions are Python - 3.6.3 (64bit) Django - 1.11.6 (64bit) Windows 10 - 64bit Thanks -
Using 'templated_docs' in Libreoffice on AWS Linux (beanstalk)
We have a running project in Debian Server which is working just fine. When we moved into AWS Linux server (using beanstalk), we faced following error: OSError: cannot load library /opt/libreoffice5.4/program/libmergedlo.so: /usr/lib64/libxml2.so.2: version `LIBXML2_GLOBAL_VARIABLES' not found (required by /opt/libreoffice5.4/program/libmergedlo.so). Additionally, ctypes.util.find_library() did not manage to locate a library called '/opt/libreoffice5.4/program/libmergedlo.so Note that we added 'templated_docs' in installed app and also added TEMPLATED_DOCS_LIBREOFFICE_PATH = '/opt/libreoffice5.4/program'. Because there was not YUM repo for Libreoffice we manually installed it and it is installed in /opt/libreoffice5.4. There is symlin in /usr/bin/libreoffice5.4. We have installed version 5.4 while we test with version 5.3 also and we got the same error. Any idea appreciated. -
Django use `super(child,self)`instead of `super()` in latest version
In Django 1.11 tutorial and documentation,there's codes style as super(child,self) everywhere. for instance: return super(ContactView, self).form_valid(form) What's the advantage of it? to reminder you in the current class for memory? -
MultiValueDictKeyError at /signup/ "'username'" in django
i created a signup page which creates users in django admin this is how my signup.html looks alike <h1>signup</h1> <form method="post" action="{% url 'signup' %}"> username: <br/> <input type="text" name="username" > <br/> passwod: <br/> <input type="password" name="password1" > <br/> confirm passwod: <br/> <input type="password" name="passwod2" > <br/> <input type="submit" value="signup"> </form> and this is how i routed using my url to views: from django.conf.urls import url from django.contrib import admin import accounts.views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^signup/', accounts.views.signup, name='signup'), and here is my views section: from django.shortcuts import render from django.contrib.auth.models import User from django.template import RequestContext # Create your views here. def signup(request): if request.method == 'POST': User.objects.create_user(request.POST.get('username') , password=request.POST.get('password1') return render (request,'accounts/signup.html') else: return render (request,'accounts/signup.html') but when i tried to run the server and enter those details regarding username and password while submitting iam getting an error called MultiValueDictKeyError MultiValueDictKeyError at /signup/ "'username'" Request Method: POST Request URL: http://127.0.0.1:8000/signup/ Django Version: 1.11.1 Exception Type: MultiValueDictKeyError Exception Value: "'username'" Exception Location: C:\Python35\lib\site-packages\django\utils\datastructures.py in __getitem__, line 85 Python Executable: C:\Python35\python.exe Python Version: 3.5.3 Python Path: ['D:\\python programs\\reddit\\redditclone', 'C:\\Python35\\python35.zip', 'C:\\Python35\\DLLs', 'C:\\Python35\\lib', 'C:\\Python35', 'C:\\Python35\\lib\\site-packages', 'C:\\Python35\\lib\\site-packages\\win32', 'C:\\Python35\\lib\\site-packages\\win32\\lib', 'C:\\Python35\\lib\\site-packages\\Pythonwin'] Server time: Wed, 1 Nov 2017 04:05:10 +0000 any kind of help is … -
Browsing to AWS machine
I have installed a Python ecommerce framework on a new AWS Linux EC2 machine using SSH. I just created this EC2 instance for this purpose. The AMI had Python 2.7 installed already on it. After I was done with the installation - the installation steps are listed here - I ran the Python webserver using python manage.py runserver and it starts at http://127.0.0.1:8000 on the EC2 instance. The problem is that I am not able to connect to the webpage from my machine, I am using the URL with the following format (without the double quotes) http://"EC2 Public DNS":8000 but I am receiving This site can’t be reached refused to connect. ERR_CONNECTION_REFUSED I have configured the security group to allow incoming traffic on the ports 8000, 80, 443 and 22 When I run netstat -punta I see 127.0.0.1:8000 listed under local address. I even ran sudo service iptables stop the sudo chkconfig iptables off to disable the firewall rules in order to rule them out as a temporary test, but still no luck! I am pretty new to AWS, Python and Linux, so I highly appreciate your help! Thank you. -
Whats the difference when add `[ ]` to regular expressions?
When I watch a video, in the 2:13 second, there is a urlpatterns: urlpatterns = [ url(r'^$', PostListAPIView.as_view(), name='list'), url(r'^(?P<pk>\d+)/$', PostDetailAPIView.as_view(), name='detail'), url(r'^(?P<slug>[\w+])/edit/$', PostUpdateAPIView.as_view(), name='update'), url(r'^(?P<slug>[\w+])/delete/$', PostDeleteAPIView.as_view(), name='delete'), ] We know we can use \d+ to match the numbers, use \w+ to match character,number,and _. But why in there the \w+ be wrap with []? can do not wrap it? And by the way, many Django model use a slug field, why use it? and the slug field has what function? whats the deep meaning of slug? -
How to change sqlite3 from django by tinyDb?
I need your help, I'm finishing a web app, in django, in which we are mining data. We realize that sqlite3 will not support the amount of data. So I started looking for databases NoSQL of the document-oriented type. Because I need quick access to the data when to search. I chose ArangoDB and TinyDB for testing. But I did not find any practical material on how to change sqlite3 by tinydb or arangodb. So I ask: How should I do? Already tried adding other NoSQL databases, such as mongodb and I did not succeed. Python reported that it was not possible to make use of the database. -
django 1.11 - how to get radio dynamic name in view?
this's my template code, I don't know how to get the input name in view.py what should I do ? {% for visitor in visitors %} VIP Black Guest {% endfor %} -
I am using Django 1.8(django-registration-redux==1.8) and keep getting redirected to /profile when trying to get to my registrations page.
I would like to be able to get to the registration page so that I can login. Page not found (404) Request Method: GET Request URL: http://localhost:8000/accounts/profile/ Using the URLconf defined in bookstore.urls, Django tried these URL patterns, in this order: ^store/ ^accounts/ ^activate/complete/$ [name='registration_activation_complete'] ^accounts/ ^activate/resend/$ [name='registration_resend_activation'] ^accounts/ ^activate/(?P<activation_key>\w+)/$ [name='registration_activate'] ^accounts/ ^register/complete/$ [name='registration_complete'] ^accounts/ ^register/closed/$ [name='registration_disallowed'] ^accounts/ ^register/$ [name='registration_register'] ^accounts/ ^login/$ [name='auth_login'] ^accounts/ ^logout/$ [name='auth_logout'] ^accounts/ ^password/change/$ [name='auth_password_change'] ^accounts/ ^password/change/done/$ [name='auth_password_change_done'] ^accounts/ ^password/reset/$ [name='auth_password_reset'] ^accounts/ ^password/reset/complete/$ [name='auth_password_reset_complete'] ^accounts/ ^password/reset/done/$ [name='auth_password_reset_done'] ^accounts/ ^password/reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>.+)/$ [name='auth_password_reset_confirm'] ^admin/ The current URL, accounts/profile/, didn't match any of these. urlpatterns = [ url(r'^store/', include('store.urls'), name='store'), url(r'^accounts/', include('registration.backends.default.urls')), url(r'^admin/', include(admin.site.urls)), ] Above is what my urls.py in my base applicaiton looks like. I tried using redirect_url in settings.py but still was not able to get to the registration page I want. -
Problems with Django SSO implementation
Is there a pre-built solution floating around that not only implements single sign on (django-mama-cas + django-cas-ng) but also auto logs in and out across the services? Meaning the domains (not subdomains) seamlessly pick up the fact I've logged in or out. I have a cas server setup, but the problem is essentially this.... Lets say I login on one domain. The other domain (if I refresh the page) doesn't pick up the ticket created until I visit (server.com/login) and then redirects me back to my original page once it sees I'm already authenticated. SO..... let's say I have a navbar with your typical conditional logic that say display register / login if not authenticated or logout if authenticated. On my other domain using the same shared code base it will display login / register until I visit the login url (and get kicked back... since I've already logged in) despite having just authenticated on the other domain. Hence, I'm looking for a way to not only have SSO implemented but have my other domains seamlessly pick up the fact that I've been authenticated through the cas server even if I didn't visit the server (to login or logout) from … -
Django changing user created data to another user?
I am having a conceptual issue in my Django project. In my scenario I have a sales team, this sales team unfortunately has high turn-over. The database works like this: Salesman Alex (user_id PK) -> has_many Clients (user_id FK) -> has_many Jobs -> has_many Notes So I am trying to structure my model with the above relationship. However, what I can't wrap my head around is what if Salesman Alex and Salesman Bob SWAP clients? What if Alex quits? The obvious answer would be to update the user_id, however, I have been reading that causes major issues. Any insight into this would be most appreciated. -
Django prevent migrations on remote database
I have a Django app that connects to two databases. One of my DBs is on a different (production) server. I want to make very sure that in developing my app, I don't accidentally migrate models on the production server. My understanding is this: Suppose my settings.py DATABASES is this: DATABASES = { 'default': {}, 'remote_db': { 'NAME' : 'important_remote_db_name', 'ENGINE' : 'django.db.backends.mysql', 'USER' : 'someuser', 'PASSWORD': 'somepass', 'HOST': : 'some.production.host.com', 'PORT' : '3306', }, 'myapp_db': { 'NAME' : 'my_app_db_name', 'ENGINE' : 'django.db.backends.mysql', 'USER' : 'localuser', 'PASSWORD': 'localpassword' } } Now suppose I also have a router class called RemoteDBRouter. Like all routers, that class will have a method allow_migrate. Note that the remote DB uses Django auth models, so the User model will have app_label 'auth', and the remote DB also has its own models with app_label 'remoteapp'. With that info, I see two possibilities for the allow_migrate method: #OPTION 1 def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == 'auth' or app_label == 'remoteapp': return db == 'remote_db' return None #OPTION 2 def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == 'auth' or app_label == 'remoteapp': return False return None Which one should I use? Option 2 is … -
Django relation lookup not creating expected query
I'm using Django 1.11.6, python 3.4.2, postgresql, PyCharm 4.5.2, and windows 10 (only for development purposes). The goal is to utilize the 'Lookups that span relationships' from the Django docs. # models class AlphaType(models.Model): page_type = models.CharField(max_length=50, primary_key=True, null=False) created_on = models.DateTimeField(auto_now_add=True) modified_on = models.DateTimeField(auto_now=True) class AlphaBoard(models.Model): title = models.CharField(max_length=50) alpha_text = models.TextField(max_length=30000) created_on = models.DateTimeField(auto_now_add=True) modified_on = models.DateTimeField(auto_now=True) fk_page_type = models.ForeignKey(AlphaType, on_delete=models.CASCADE, default='general') #views .... q = AlphaBoard.objects.filter(fk_page_type__page_type='general') print(q.query) .... Just fyi, the tables have the app name prepended to the model name and the foreign key has 'id' appended to the foreign key column name. Result of the query print. SELECT "alpha_alphaboard"."id", "alpha_alphaboard"."title", "alpha_alphaboard"."alpha_text", "alpha_alphaboard"."created_on", "alpha_alphaboard"."modified_on", "alpha_alphaboard"."fk_page_type_id" FROM "alpha_alphaboard" WHERE "alpha_alphaboard"."fk_page_type_id" = "general" What I was expecting. SELECT "alpha_alphaboard"."id", "alpha_alphaboard"."title", "alpha_alphaboard"."alpha_text", "alpha_alphaboard"."created_on", "alpha_alphaboard"."modified_on", "alpha_alphaboard"."fk_page_type_id" FROM "alpha_alphaboard" INNER JOIN "alpha_alphaboard" ON "alpha_alphatype" "alpha_alphaboard"."fk_page_type_id" = "alpha_alphatype"."page_type" WHERE "alpha_alphatype"."page_type" = "general" Questions Why is the query ignoring the page_type relation from the filter? Look at the result of the printed query and the filter within the views. I should also add that I had a related_name="fk_page_type" within the AlphaBoard.fk_page_type, but I removed it. So a follow up question is why is it still picking up the related_name? How do you use … -
Django: Class-based views, URL and template_name
I am trying to use something like polls:detailin a class-based view, such as this: class QuestionDetail(DetailView): template_name = 'polls:result' However, I get a TemplateDoesNotExist at /polls/2/result polls:result error... The urls.py is: from django.conf.urls import url from polls.views import IndexView, DetailView, ResultsView from . import views app_name = 'polls' urlpatterns = [ url(r'^$', IndexView.as_view(), name='index'), url(r'^(?P<pk>\d+)/$', DetailView.as_view(), name='detail'), url(r'^(?P<pk>\d+)/result$', ResultsView.as_view(), name='result'), url(r'^(?P<pk>\d+)/vote$', views.vote, name='vote'), ] I guess the main question is, how do I use the names of URLs in class-based views, instead of explicitly providing the template name, such as polls/question_results.html? Is there anything other than template_name? I was reading that it's a good practice to use names in URLS so in case the URL itself changes, the rest of the code still works, so that's what I'm trying to do. -
django with multiple databases and foreignkeys for User
Suppose I have a django app on my server, but I wish to do authentication using django.contrib.auth.models where the User and Group models/data are on another server in another database. In Django, my DATABASES setting would be something like this: DATABASES = { 'default': {}, 'auth_db': { 'NAME' : 'my_auth_db', 'ENGINE' : 'django.db.backends.mysql', 'USER' : 'someuser', 'PASSWORD' : 'somepassword', 'HOST' : 'some.host.com', 'PORT' : '3306', }, 'myapp': { 'NAME': 'myapp_db', 'ENGINE': 'django.db.backends.mysql', 'USER': 'localuser', 'PASSWORD': 'localpass', } } DATABASE_ROUTERS = ['pathto.dbrouters.AuthRouter', 'pathto.dbrouters.MyAppRouter'] First question: will this work, ie will it allow me to login to my Django app using users that are stored in the remote DB 'my_auth_db'? Assuming the answer to the above is yes, what happens if in my local DB (app 'myapp') I have models that have a ForeignKey to User? In other words, my model SomeModel is defined in myapp and should exist in the myapp_db, but it have a ForeignKey to a User in my_auth_db: class SomeModel(models.model): user = models.ForeignKey(User, unique=False, null=False) description = models.CharField(max_length=255, null=True) dummy = models.CharField(max_length=32, null=True) etc. Second question: Is this possible or is it simply not possible for one DB table to have a ForeignKey to a table in another … -
"Generate" client to use Django restful API
I have programmed a Django application that provides a RESTful API via Django Restful Framework. Now I need to create a "client" that uses the API. This client will also be written in Python but run on a different machine than the app. As the application I already have contains most of the required information how the API can be consumed (i.e. the Django model), it seems possible to "generate" the client code automatically to a large extent. Similar to how the Django Restful Framework "generates" the API code from the model. This would save me from having to use the (awesome, I admit) Request module and write a lot of code myself. I assume I could use the Django Restful Framework's Serializers, etc. to have a head start, but that would mean that the client must have Django installed. That is something that will not be possible. What is the best/easiest/preferred/pythonic way to write a (slim) client to consume a Django RESTful API? -
adding {% static '<File_Name>' %} to many entries in DJango
I need to add the "static" feature to a number of files in my DJango project as mentioned here: howto: static files It seems to work. But, the instruction says that one needs to make this change OLD: <img src="my_app/example.jpg" alt="My image"/> NEW: {% load static %} <img src="{% static 'my_app/example.jpg' %}" alt="My image"/> to every line that needs it. I have several hundred lines of already-existing code that is in the old format. How can one change so many lines so at one time so that they will be in the correct format? TIA -
is there a way to convert a view function to a celery task?
task.py @task(name="send_mail_to_custormer") def order_created(order_id): order = Order.objects.get(id=order_id) subject = 'Order nr. {}'.format(order.id) message = 'Dear {} {},\n\nYou have successfully placed an order. Your order id is {}'.format(order.first_name, order.last_name, order.id) from_email = settings.EMAIL_HOST_USER to_email = [order.email] mail_sent = send_mail( subject, message, from_email, to_email, fail_silently=False ) return mail_sent views.py def order_create(request): cart = Cart(request) if request.method == 'POST': form = OrderCreateForm(request.POST) if form.is_valid(): order = form.save() for item in cart: try: OrderItem.objects.create(order=order, product=item['product'], price=item['price'], quantity=item['quantity']) except: pass cart.clear() order_created.delay(order.id) return render(request,'orders/order_created.html', {'cart': cart, 'order': order}) else: form = OrderCreateForm() return render(request, 'orders/order_create.html', {'cart': cart, 'form': form}) cart.py class Cart(object): def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def add(self, product, quantity=1, update_quantity=False): product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'price': str(product.price)} if update_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() def save(self): self.session[settings.CART_SESSION_ID] = self.cart self.session.modified = True Now the celery task sends mail and view function creates order after taking values from cart and order form. How I can change the task to create order? Is it a good practice doing so. Hope somebody can help me, thank you. -
Django save override recursion not working
I'm trying to set up a promo code system that automatically gets claimed by eligible users/students (specified either by a M2M or comma separated string of emails). Here's the relevant code from the model: class PromoCode(models.Model): students_claimed = models.ManyToManyField('Student', blank=True, related_name='promo_codes_claimed') claimable_by = models.ManyToManyField('Student', blank=True, related_name='claimable_promo_codes') claimable_by_emails = models.CharField(max_length=10000, null=True, blank=True) def save(self, *args, **kwargs): if self.claimable_by_emails: for email in self.claimable_by_emails.split(','): try: student = Student.objects.get(user__email=email) student.claim_promo_code(self) except Student.DoesNotExist: pass for student in self.claimable_by.all(): student.claim_promo_code(self) super().save(*args, **kwargs) The claim_promo_code method within Student is as follows: def claim_promo_code(self, promo_code): if promo_code.is_claimable_by(self): promo_code.students_claimed.add(self) promo_code.save() print('TEST') I know the claim_promo_code method is being called because the print statement is running; however, the user is not being added/saved to students_claimed. Calling the claim_promo_code method through other means (outside of the save method) works as intended. Is there a problem with calling an object's save method within itself, as is the case here? How should I approach solving this? -
CSS styling got ruined while sending html mail using python via sendgrid
When I send HTML template as a mail, all the styling got ruined. The html is created using sendgrid templating but all the styling got ruined when I send this email. Here is my code. main.py from django.template.loader import render_to_string def send_mail(receiver_email, subject, email_template): sendgrid_object = sendgrid.SendGridAPIClient(apikey = credentials.sendgrid_API_key) data = { "personalizations": [ { "to": [ { "email": receiver_email } ], "subject": subject } ], "from": { "email": "support@xyz.net", "name": "Support" }, "content": [ { "type": "text/html", "value": email_template } ] } response = sendgrid_object.client.mail.send.post(request_body=data) send_mail(email,subject, render_to_string("welcome.html"))