Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I want to integrate travel agency API's(like Make my trip, Yatra.com) into my Django project of holiday resort booking ?How this can be done?
I'am making a project for resort bookings and i need to integrate make my trip and yatra.com for various offers. As far as i've researched there isn't an api for these things. Please help me. Thanks in advance. -
Django Two apps are sharing their templates
In my django project there has 6 apps installed. Among them 2 of them are sharing their templates. While creating app 1 view and rendering with app 2 templates it first searching whether there any .html template on app 1 template folder if not then it's bringing it from app 2. Same goes for app 2. But if trying with other applications templates folder's .html file it's show TemplateDoesNotExist. How it possible that 2 app are sharing their template while i haven't written any code for this ??? -
Django admin limit rights
In my Django project I have the models Project, Person, Task and Info. Thing is, however, that the Project is the parent model. Person, Task and Info belongs to the Project. If I add a Person, Task or Info I have to choose the Project (ForeignKey) it belongs to. My problem: Those projects are independent and I have different project managers. My goal is that in the admin interface the project manager of project A for example can only add a Person to HIS project, same with Info and Task. I don't want that the project manger of project A can see/edit/add/delete things of project B. Unfortunately, I could not find options in the Django admin that meets my requirements. If the project manager logs in he should only see instances that belongs to his project, nothing else. How would you solve that issue? -
Wagtail: accessing data models outside of an app
Very simple really. But I'm new to django and be extension wagtail too. I want to display the posts from an app on the homepage, or within any other django app for that matter. Current app structure: website/home/ website/blog/ website/portfolio/ Currently I can easily display the posts from 'web_development items' in a nice for loop on the 'web_development index page'. When I try to extend this to the homepage, nothing works. How do I access the models, etc of one app from another (in this case the 'home' app. Portfolio modelss.py: from __future__ import unicode_literals from django.db import models from django import forms, utils from wagtail.wagtailcore.models import Page from wagtail.wagtailcore.fields import RichTextField from wagtail.wagtailsnippets.models import register_snippet from wagtail.wagtailadmin.edit_handlers import FieldPanel, InlinePanel, MultiFieldPanel, PageChooserPanel from wagtail.wagtailimages.models import Image from wagtail.wagtailimages.edit_handlers import ImageChooserPanel from modelcluster.fields import ParentalKey, ParentalManyToManyField from modelcluster.tags import ClusterTaggableManager from taggit.models import TaggedItemBase, Tag as TaggitTag class PortfolioHome(Page): description = models.CharField(max_length=255, blank=True,) content_panels = Page.content_panels + [ FieldPanel('description', classname="full"), ] class PortfolioPage(Page): body = RichTextField(blank=True) feature_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) categories = ParentalManyToManyField('portfolio.PortfolioPageCategory', blank=True) tags = ClusterTaggableManager(through='portfolio.PortfolioPageTag', blank=True) pub_date = utils.timezone.now() content_panels = Page.content_panels + [ FieldPanel('body', classname="full"), FieldPanel('categories', widget=forms.CheckboxSelectMultiple), FieldPanel('tags'), ImageChooserPanel('feature_image'), ] Homepage models.py: … -
Passing string over urls django
I'm having trouble in understanding this error in my code, first let me try and explain what is happening and what I'm I trying to do. My code is designed to load up 45 separate text files into an array, including the weight of each word/phrase and the word phrase itself. This has to occur at the beginning, before any description is received. Second, once the description is received, it is parsed by my software into words/phrases, which are compared to the words/phrases in the array. Third, my software then provides the top three classes, in rank order (first/second/third) by number, along with the score for each class. I've made a django application that will serve this code, so I have a form which will provide two parameters classes and description, like this: class TrademarkClassifierForm(forms.Form): """ TODO: This forms will cover the questions the initial classifier program does :returns: TODO """ classes = forms.CharField(max_length=10, label="Test all trademark classes? Type 'yes' to do so or else enter the class to be tested ") description = forms.CharField(widget=forms.Textarea) def __init__(self, *args, **kwargs): super(TrademarkClassifierForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.add_input(Submit('submit', 'Submit')) Then I want to pass this two parameters in the view over the … -
Django all url SSL
I have setup a django application on digitalocean with minimal nginx and gunicorn setup. I am managing my dns using cloudflare and also using cloudflare's flexible ssl. Now the problem is all of my django generated urls have http url(http://example.com/favicon.ico), how can I make all url https? -
celery error :'module' object has no attribute 'celery'
I try to start celery using command below: celery -A converter worker --loglevel=info but it doesn't work. my converter.py is: from __future__ import absolute_import, unicode_literals from celery.task import task @task def ffmpeg_convert(input_file, bitrate): #do something and my celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings.base') app = Celery('converter') app.config_from_object('django.conf:settings', namespace='CELERY') app.conf.broker_url = 'redis://localhost:6379/0' app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) but I get following error: Traceback (most recent call last): File "/usr/local/bin/celery", line 11, in <module> sys.exit(main()) File "/usr/local/lib/python2.7/dist-packages/celery/__main__.py", line 14, in main _main() File "/usr/local/lib/python2.7/dist-packages/celery/bin/celery.py", line 326, in main cmd.execute_from_commandline(argv) File "/usr/local/lib/python2.7/dist-packages/celery/bin/celery.py", line 488, in execute_from_commandline super(CeleryCommand, self).execute_from_commandline(argv))) File "/usr/local/lib/python2.7/dist-packages/celery/bin/base.py", line 279, in execute_from_commandline argv = self.setup_app_from_commandline(argv) File "/usr/local/lib/python2.7/dist-packages/celery/bin/base.py", line 481, in setup_app_from_commandline self.app = self.find_app(app) File "/usr/local/lib/python2.7/dist-packages/celery/bin/base.py", line 503, in find_app return find_app(app, symbol_by_name=self.symbol_by_name) File "/usr/local/lib/python2.7/dist-packages/celery/app/utils.py", line 366, in find_app found = sym.celery AttributeError: 'module' object has no attribute 'celery' Do anyone has any idea?Thank for help -
how to return user from django-rest-framework-social-oauth2 convert token view?
I am currently using Django-rest-framework-social-oauth2 and it's convert-toke endpoint. I send user token from Facebook with the request to this end point which on success, responds with the following data: { "access_token": "************", "token_type": "Bearer", "expires_in": 36000, "refresh_token": "************", "scope": "read write" } However, I also want to get the id of authenticated user, So I tried using request.user in the custom view, but it always return AnonymousUser. class SocialView(ConvertTokenView): def post(self, request, *args, **kwargs): response = super(SocialView, self).post(request, *args, **kwargs) -
Get related_name between two models
How can I programmatically get the related_name or related_query_name from a Django model to another model? For example, in this code how can I get the name that Parent uses to reference Child with? class Parent(models.Model): title = models.CharField(max_length=10) class Child(Parent): parent = models.OneToOneField(to=Parent, parent_link=True) description = models.TextField() -
RECEIVING email from Django website
I would like to enable people that visit my website to be able to send me an email to my yahoo mail. How can I do this? Now, I don't have a mail server (yet). Would it be necessary? The idea is for the person sending the email to fill in his email, subject and message, and then it would be posted to my yahoo email. def email(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = request.POST.get['subject'] email = request.POST.get['email'] message = request.POST.get['message'] if subject and email and message: try: send_mail(subject, message, email, ['my_email@yahoo.com'], fail_silently=False,) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('thanks') else: return HttpResponse('Make sure to have all fields filled.') return render(request,"mywebsit/contact.html", {'form':form}) The form renders ok, but when I press send it acts as if it has sent the message, but when I open my yahoo mail there's nothing new there. I read it would be necessary to configure some things at settings.py, but, as far as I get it, it is meant to SEND, whereas what I want is to RECEIVE. Inspite of that, I tried configuring it, EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.mail.yahoo.com' EMAIL_PORT = 465 EMAIL_HOST_USER = … -
Testing database in django other than django models
I am using mysql-server and MySQLdb for accessing my database. I have not even used django models to accessing the database tables. Now the problem comes while testing. All the django documentation is talking about the testing using django models. While testing a data, i have to insert data into the database using cursor.execute() function then i have to read from that. But this waste out my time. Also TestCase class run all database query in transaction and my doubt is that, this will be same for mysql-server and myqldb? I am using MySQLdb since it is faster than django models. Can anyone tell me how can i make the testing simpler ? How can i test the database in django? -
How do I update a form having select option in Flask (Python)
My question is about how to update select option in flask. I have created a registration form which contains select option to select Department. There are four options in department, the selected value is getting stored in MySQL database. This is working perfectly. Now I need update user page where user can update their details. The options are static and not fetching from database, only selected value is getting stored. Is it possible to get the form select option as pre-selected? <div class="input-group" style="margin-bottom: 5px;"> <label class="input-group-addon">Department:<span style="color: red">*</span> </label> <select name='employee_status' class="form-control"> <OPTION selected value='Sales'>Sales</OPTION> <OPTION value='Marketing'>Marketing</OPTION> <OPTION value='Support'>Support</OPTION> <OPTION value='Development'>Development</OPTION> </select> </div> Thanks in advance. -
Using Matplotlib with Django
I have built a simple web application using Django that reads a csv file and allows users to plot graphs by selecting X & Y attributes. The frontend makes use of AJAX calls to call backend methods to plot graphs using Python's Matplotlib. The issue arises when the plots are called asynchronously, causing a race condition: Different charts get plotted to the same figure. In attempts to overcome this problem, I assign random "id" to each user so that I can call matplotlib to get a figure number -- So each user plots on different figures. import matplotlib import pandas as pd matplotlib.use('agg') def plot_graph(id, args) fig = plt.figure(id) # This method plots a graph on 2 axes However, this does not solve the problem -- When a user plots 3 graphs at one time the graphs overlap on each other. -
Graphene Django without Django Model?
I've successfully used Graphene-Django to successfully build several GraphQL calls. In all of those cases I populated, in whole or in part, a Django model and then returned the records I populated. Now I have a situation where I'd like to return some data that I don't wish to store in the Django model. Is this possible to do with Graphene? Robert -
get_search_results : AssertionError Cannot reorder a query once a slice has been taken
In my Django Admin, i set a feature where the admin can search for products with certain category, so when i search "BreastPad", it will show products that have name of BreastPad, but if i search "category:Bra", it will look for products that have category of Bra. Now here is the problem, when the total of the products is bigger than the "list_per_page", i always get this error: AssertionError at /admin/ecoommerce/product/ Cannot reorder a query once a slice has been taken. For now i fixed the error simply by keep adding the list_per_page from 50 to 100, and now 200. I tried to simply just cut the total products to 50 by using all_products[:50] when the list_per_page is 50, but it still shows that "cannot reorder a query once a slice has been taken" exception. Please help. def get_search_results(self, request, queryset, search_term): # check if string contains the word category:XXXXXXXXXXXX if "category:" in search_term: # remove the word category: the_searched_category = search_term[9:] # search Product_category with that name the_searched_category = Product_TW.objects.all().filter(name=the_searched_category).first() if the_searched_category != None: all_products = Product_TW.objects.all().filter(product_categories__in=[the_searched_category]).distinct() return all_products, True else: return Product_TW.objects.none(), True else: queryset, use_distinct = super(Product_Admin, self).get_search_results(request, queryset, search_term) return queryset, use_distinct list_per_page = 100 -
How to store information to link user profile and paypal account - django
I am building a django project that will allow users to send money from one paypal account to a company paypal account to temporarily hold the money that is sent. My big thing is that I dont want the user to have to login to the paypal account every time they are sending money because they will be doing it quite often. Is there a way to some how permanently link a user account within a django application to the users paypal account so that they dont have to keep loggin in. I know storing login information in the database is a big NO NO and i should do that, but i was wondering if anyone knows a way I can accomplish what I want in a secure manner to protect the users credentials.. Thank you for your help... -
Django class-based UpdateView
We are using Django 1.9.5. I am writing update company profile view. I want to have two fields on my update profile page: company name, apikey(generated with a dedicated function). I want to change field name by hands and then save by clicking button Update. For filed apikey I want to have separated button which would automatically generate new key, save it to db and update my page. I am overwriting post method at UpdateView class. But simething isn't working. Please take a look at my code: models.py: class Organization(models.Model): name = models.CharField(_('organisation display name'), max_length=512, blank=True) apikey = models.CharField(_("API authentication key"), max_length=APIKEY_LENGTH, default=get_apikey) where get_apikey is from django.utils.crypto import get_random_string APIKEY_PREFIX = "key-" APIKEY_LENGTH = 80 def get_apikey(): rnd_len = APIKEY_LENGTH - len(APIKEY_PREFIX) return "{}{}".format( APIKEY_PREFIX, get_random_string(rnd_len, "abcdefghijklmnopqrstuvwxyz0123456789") ) forms.py: from django import forms from crispy_forms.helper import FormHelper, Layout from orgs.models import Organization class OrgProfileForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(OrgProfileForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False class Meta: model = Organization fields = ['name', 'apikey'] views.py from django.views.generic.edit import UpdateView, BaseUpdateView from orgs.forms import OrgProfileForm from orgs.models import Organization from local.auth import get_apikey class OrgProfileView(UpdateView): model = Organization template_name = 'orgs/orgprofile.html' form_class = OrgProfileForm url_name = 'profile' … -
Do i need use https in django restful api?
I use django restful api in my project . The DEFAULT_AUTHENTICATION_CLASSES is set 'rest_framework.authentication.SessionAuthentication' My api is : http://172.100.0.48:8000/api/test/ DO i need https? if I need how to config it ? -
Django form saving all values to 0 when I change just one
I have gotten the application to look as I want on the screen but the form won't save correctly. The end goal is to have a dynamically generated table, with some td's being editable fields, based off of data in a few models. First my "Project" model gives a start date and end date for a project which is turned into start and end dates for each week. This is passed as the start and end date for the function in question. The function below takes those dates and generates values and form fields based on the associated objects in my "Allocation" model. This model contains records of each unique allocation: class Allocation(models.Model): user_id = models.ForeignKey(Resource) project_id = models.ForeignKey(Project) week = models.DateField(default=timezone.now) allocated_hours = models.IntegerField(default=0) actual_hours = models.IntegerField(default=0) The below function is displaying model fields with initial data for any user during a date range where they are allocated hours on a given project. It is also creating blank model fields for any where the user is not allocated and puts an initial value of 0. Everything looks fine on the page, but when I change a value and click save, all fields are saved in the db with 0. … -
Django + Postfix reset password email not beeing sent
I have set a django app in my cloud server and I'm trying to configure it to send password reset emails. First I configured my views and tested them with the django console e-mail backend EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' And it's working, I can see the e-mail sent to my console when I visit the password reset view. Next I configured postfix to be my backend. Postfix is working and I receive the e-mails I send with this command: echo "Body" | mail -s "Subject" myemail@gmail.com After this I changed my django settings.py to use postfix like this EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'localhost' EMAIL_PORT = 25 EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL_USE_TLS = False DEFAULT_FROM_EMAIL = 'Noreply <noreply@mydomain.com>' If I use python manage.py shell and run: from django.core.mail import send_mail send_mail('Subject', 'Body', 'noreply@mydomain.com', ['myemail@gmail.com'], fail_silently=False) I am also able to receive the e-mail. However when I go to my site password reset view I am not getting any e-mails sent! In journalctl -u postfix -xe I get the following messages: postfix/smtpd[23411]: connect from localhost[127.0.0.1] postfix/smtpd[23411]: 7BAED13D02E: client=localhost[127.0.0.1] postfix/cleanup[23414]: 7BAED13D02E: message-id=<20170820234125.23051.46440@mydomain.com> postfix/qmgr[20567]: 7BAED13D02E: from=<noreply@mydomain.com>, size=974, nrcpt=1 (queue active) postfix/smtpd[23411]: disconnect from localhost[127.0.0.1] ehlo=1 mail=1 rcpt=1 data=1 quit=1 commands=5 postfix/smtp[23415]: connect … -
Whats the difference iterating over the queryset in these two ways?
I was using Django for building my project and came across these two ways. One way is : users = Users.objects.filter(is_verified=True) for user in users: print user.user.id And the second way is : users = Users.objects.filter(is_verified=True) for user in users: print user.id At first I thought the first way wont work but it was working and was quite slow then the second way. -
Django Web App Code works on local dev machine but not when deployed to server
I have a Django web project that i am working on which overall has gone pretty smoothly. I have a view below which grabs objects from the database and displays them via a template to the user. def index(request): all_occurrences = Occurrence.objects.all().order_by("-pk") calculate_percentage_right() context = { 'all_occurrences': all_occurrences, 'percentage_right': calculate_percentage_right() } query = request.GET.get("q") if query: all_occurrences = all_occurrences.filter( Q(Subject__icontains=query) | Q(Details__icontains=query)) return render(request, 'wrong/wrong_view.html', { 'all_occurrences': all_occurrences, }) else: return render(request, 'wrong/wrong_view.html', context) The issue that is occurring which to me makes no sense to me is that I am using a function to calculate a percentage right which is based on an object attribute called "timewrong". When I run this on my local machine it performs as expected, when I deploy this to my web server which is hosted on an Amazon EC2 Instance it does not calculate the percentage correctly. I either get 100% or 0% no in between. I have verified that on the webserver it is seeing all of the variables I have created correctly. The problems appears to occur when the division happens to get me to the percentage. def calculate_percentage_right(): wrongs = Occurrence.objects.all() total_minutes_wrong = 0 for wrong in wrongs: total_minutes_wrong += wrong.TimeWrong … -
Draw a map of a specific country with leaflet in django
I am new to concept of maps and would like to create a leaflet map that only displays one country and possibility to add polylines or waypoints on top of that. This has been done in R, but I can't quite grasp on how to do that in python yet. Draw a map of a specific country with leaflet I have geoJSON file of the contry border. -
How to Reload django model
I have a modelChoice field in my django model class whose choices is based on another model values. each time i add new entries to the latter model, the value does not reflect on my page untill i restart the server. below is my code: from multiselectfield import MultiSelectField class FirstModel(models.Model): choices = [(x.pk,x.subject_title) for x in Subject.objects.all()] choices = tuple(choices) subjects_to_offer = MultiSelectField(choices=choices) class Subject(models.Model): # field declarations now each time i update the Subject, the values does not reflect on the page until i restart the server. please how do i reload the First model without restarting the server. Many tanks P.S the MultiSelectField is package from https://github.com/goinnn/django-multiselectfield it is just like a choice field except it has some added features. if only i can figure a way of reloading the models without restarting the server then i'll be fine -
Django: Restrict access to page
In my Django project I have Products. You can access products using this url pattern: example.com/tshirt or example.com/jacket etc. Moreover, you can view some other pages for those products, i.e.: example.com/tshirt/details or example.com/jacket/buy My problem: When I create a new product in my admin interface, the product is deactivated by default (I can activate it later). The reason is that when I create a new product I often don't have all necessary information yet (i.e. price). As long as a product is deactivated all URLs starting with example.com/this-one-product should not be visible for the normal visitor (getting 404 error). Unfortunately, I don't know how to do that. My goal is that it's visible for the super user or users from the staff. Because it makes sense that they can check that product and see how it looks like when it's rendered. But, as said, it should not be visible for the normal visitor of the webpage. Now I could of course create if statements in all those views (and check if superuser or from staff), but that does not sound like a elegant solution. Because I would have to add those statements to many different views and that's against DRY …