Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Restricting Access to Django's success_url()
new Django user here. I am trying to restrict access to Django's success_url() upon GET requests. I realize I am not the first to ask this question, however, I am specifically trying to achieve this in conjunction with Django's generic class-based views. Generic view seem cleaner, faster, and more idiomatic. I want to use them as much as possible unless they are absolutely unfit for the job. Basically, I am creating a simple contact form for non-users who only want to send me a message without creating an account. I've created a contact app to handle these types of contacts. I've created a ModelForm, which I am rendering with a contact.html with Django's FormView. After a person submits the form, they will receive a cool looking thank you message, rendered with a thanks.html, which has its own url. But I only want them to see the thank you message if they POST the contact form. Currently, you can go on my site and type '/contact/thanks/', and my thanks.html will be rendered whether you've submitted a form or not. Django's success_url apparently defaults to a GET request. Here's my view: class MyContact(FormView): template_name = 'contact.html' form_class = ContactForm success_url = 'thanks' … -
Display then editable choice field from Django template
i want to build a function like this. In which user can change their initial choice field. Does anyone can help me, now i build choice field in admin form and problem is that how to allow user edit their choice field from django template enter image description here -
Annotating count of unique object occurences in Django ORM query
In a Django app of mine, users post photos saved as photo objects. Viewers can then post comments under each photo, saved as photocomment objects that have a foreignkey on photo objects. I'm trying to write an ORM query where to each photo object requested, I append the number of unique comments it garnered. Unique implies comment by a unique user_id. I.e. if the same guy/girl commented 1000 times, it' still 1 unique comment. How do I accomplish that? So far, I've come up with the following: relevant_photos = Photo.objects.filter(id=set_of_ids) PhotoComment.objects.filter(which_photo_id__in=relevant_photos).annotate(unique_comment_count=Count("submitted_by")).distinct("submitted_by") I feel this can't work because I'm not really counting distinct commenters here. What would be the correct way to do this? Trying to wrap my head around it. -
Once I know basic Python (MITx: 6.00.1x), what should I learn/use to programming a text processor?
I finished MITx: 6.00.1x Introduction to Computer Science and Programming Using Python almost 2 months ago. It seems I have to refresh some basic things now but I'm starting to play a little with some other resources, and starting with MITx: 6.00.2x, HarvardX: PH526x Using Python for Research. Yet I'll probably learn best by developing some projects I'm interested in. Those were in fact my motivation to learn. The one I'm most in need to develop is a text processor with some special features that should work first for an individual using it. I will learn some NLP with Python and at some point it will become a collaborative text processor where several people could work on it. What do you recommend to start doing/learning/using? I'd rather spent more time learning something to make a good app/soft that many people would adopt, than doing something faster just for learning that just me would use it... Unless this is something I could improve with time in a lean programming fashion... For example, I can't even figure out how to set up a page, like the white background A4 sheets you can set in any non-programming text processor like Word, LibreOffice Writer … -
Exporting HTML to PDF and send the generated PDF via email in DJANGO
I am using Django 1.10.3 and Reportlab to export html to pdf now I want to email the same generated pdf.I was able to generate the pdf but unable to email it. Please help me achieve it. Here is my view: def write_pdf_view(request): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'inline; filename="mypdf.pdf"' buff = StringIO() menu_pdf = SimpleDocTemplate(buff, rightMargin=72, leftMargin=72, topMargin=50, bottomMargin=18) elements = [] styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='centered',fontName='Italic', alignment=TA_CENTER)) elements.append(Paragraph('A good thing about WeasyPrint is that you can convert a HTML document to a PDF. So you can create a regular Django template, print and format all the contents and then pass it to the WeasyPrint library to do the job of creating the pdf.', style=styles["Normal"])) menu_pdf.build(elements) response.write(buff.getvalue()) buff.close() return response -
Django Admin site paginator does not appear
I'm setting up a django paginator in the Django Admin Site in order to display the elements 30by30 on the changelist. To do so, I'm using "list_per_page=30" on the DocumentAdmin. It works fine on Firefox, but the paginator doesn't appear on Safari, either in iMac, iPad or iPhone... so I can only see the first 30 elements. However, it does appear when I reduce the amount of elements I want to display, for instance, 8. I have similar problems using Chrome. Am I missing something? Any help is really welcome. Thanks for your time. -
Queryset filtering on Foreignkey in Modelform
I have a strange issue when saving a model form. I have a form, which consists of two model forms and i am trying to save them at the same time. For clarity, below is my code Views.py def create_user(request): if request.method == 'POST': user_form = UserForm(request.POST) my_user_form = MyUsersForm(request.POST) if user_form.is_valid() and my_user_form.is_valid(): us = user_form.save() my_us = my_user_form.save(commit=False) my_us.user = us my_us.save() return HttpResponse('You have successfully created a user') else: return HttpResponse(' My_user_form is not validated') else: user_form = UserForm() my_user_form = MyUsersForm(user=request.user) return render(request, 'create_user.html', {'user_form': user_form, 'my_user_form': my_user_form}) my_user_form is not validated when i override the init method of MyUsersForm to filter the queryset of the foreign key(created_by) but, when i don"t filter the queryset, my_user_form is validated and the form is saved. What i don't understand is when i don"t filter the query set how come my_user_form is validated? The data which is sent via the request.post to my_user_form is somehow lost (when i filter the queryset). any clue in the right direction is highly appreciated. Thank you. Forms.py class MyUsersForm(ModelForm): class Meta: model = MyUsers fields = ['created_by', ] def __init__(self, user=None, **kwargs): super(MyUsersForm, self).__init__(**kwargs) if user is not None: self.fields['created_by'].queryset = User.objects.filter(username=user) Models.py … -
How to optimise number of queries when using raw_id_fields in Django Admin
I have a data model as below: class Candidate(models.Model): name = models.CharField() class Skill(models.Model): name = models.CharField() class CandidateSkill(models.Model): candidate = models.ForeignKey(Candidate) skill = models.ForeignKey(Skill, related_name='candidate_skills') name = models.CharField() And in the admin I have: class CandidateSkillInline(admin.TabularInline): model = CandidateSkill fields = ('skill', ) extra = 0 raw_id_fields = ('skill',) class CandidateAdmin(admin.ModelAdmin): model = Candidate fields = ('name',) inlines = [CandidateSkillInline] Each candidate can have many skills. The problem here is that the for each inline one query will be used to fetch the skill (SELECT ••• FROM "skill" WHERE "skill"."id" = <id>). If I add the field skill in CandidateSkillInline as read_only then there won't be extra queries. However I'd like to be able to add new items in the inlines. Thing I've tried: 1) Added custom formset to CandidateSkillInline: class CandidateSkillInlineFormset(BaseInlineFormSet): def __init__(self, *args, **kwargs): super(CandidateSkillInlineFormset, self).__init__(*args, **kwargs) self.queryset = self.queryset.select_related('skill') 2) Override the get_queryset on the inline: def get_queryset(self, request): super(CandidateSkillInline, self).get_queryset(request).select_related('skill') 3) Override the get_queryset on CandidateAdmin: def get_queryset(self, request): return super(CandidateAdmin, self).get_queryset(request).prefetch_related('candidate_skills__skill') However, still I get a query for each skill. The only way the queries are not sent is when I set the skill in read_only_fields in CandidateSkillInilne. The question is how can I … -
How to stop celery task while it is being executed and continue the execution after some time?
I have the following celery task(simplified), which interacts with Twitter API. @app.task def get_followers(screen_name, **kwargs): cursor = kwargs.get('cursor', -1) followers = kwargs.get('followers', []) while True: response = twitter_api.call('followers', 'ids', screen_name=screen_name, cursor=cursor) if response.status_code == '429': # RATE LIMIT EXCEEDED # do something here cursor = response.json()['next_cursor'] if cursor == 0: # we're done break return followers I want to be able to pause task for some time when the rate limit is hit, and resume the execution from the point where it left off. (Or throw an error and retry the task, passing in additional kwargs). How can this be accomplished? -
Django - where put argparse command to modify -h option?
I would like to modify my help option in project I created. I put argparse in manage.py file, like this parser = argparse.ArgumentParser( description="Some desc", formatter_class=argparse.RawTextHelpFormatter ) args = parser.parse_args() print(args) if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Reporter.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv) but when I run python manage.py -h it works correctly (help shows), but when I run python manage.py runserver, I got: manage.py: error: unrecognized arguments: runserver How to solve this problem? I really don't know how to modify -h option. Where should I put argparse code to get help in this django project? I know I can use own command, but it is important to me to get help after I make python manage.py -h -
No Module Named Extern
I am having real trouble trying to use pip to install pyserial for python 3.5.2, I am trying to install pip using 'sudo easy_install pip'. I keep getting this error message: sudo easy_install pip Traceback (most recent call last): File "/usr/local/bin/easy_install", line 11, in load_entry_point('setuptools==29.0.1', 'console_scripts', 'easy_install')() File"/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/init.py", line 565, in load_entry_point return get_distribution(dist).load_entry_point(group, name) File"/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/init.py", line 2697, in load_entry_point return ep.load() File"/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/init.py", line 2370, in load return self.resolve() File"/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources/init.py", line 2376, in resolve module = import(self.module_name, fromlist=['name'], level=0) File "build/bdist.macosx-10.12-intel/egg/setuptools/init.py", line 10, in File "build/bdist.macosx-10.12 intel/egg/setuptools/extern/init.py", line 1, in ImportError: No module named extern Any Help would be appreciated. -
Exporting HTML to PDF and sending via email in DJANGO
I am using Django 1.10.3 and Reportlab to export html to pdf now I want to email the same generated pdf.I was able to generate the pdf but unable to email it. Please help me achieve it. -
Replacement for filterby in vuejs 2
I am using django with vue js. I am following a tutorial for vue js and they have used vuejs 1 and I wanted to use vuejs 2. How to change this statement from vuejs1 to vuejs2? v-for=" (story,index) in stories | filterBy 'Alex' in 'writer " This is my whole code. I am using django so mind the curly braces are replaced by [[ value ]]. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Learning Vue</title> <link href="/static/vendor/bootstrap/css/bootstrap.css" rel="stylesheet"> </head> <body> <div class="container"> <h1>Let's hear some stories!</h1> <div> <h3>Alex's Stories</h3> <ul class="list-group"> <li v-for=" (story,index) in stories | filterBy 'Alex' in 'writer " class="list-group-item"> [[index+1]]. [[ story.writer ]] said "[[ story.plot ]]" </li> </ul> </div> <div> <h3>John's Stories</h3> <ul class="list-group"> <li v-for=" (story,index) in stories | filterBy 'Alex' in 'writer " class="list-group-item"> [[index+1]]. [[ story.writer ]] said "[[ story.plot ]]" </li> </ul> </div> <pre> [[ $data | json ]] </pre> </div> </body> <script src="/static/vendor/vue.js"></script> <script> new Vue({ delimiters: ["[[", "]]"], el:'.container', data:{ stories: [ { plot:'I crashed my car today!', writer: 'Alex' }, { plot:'Yesterday,someone stole my bag!', writer:'John' }, { plot: 'Someone ate my chocolate...', writer: 'John' }, { plot: "I ate someone's chocolate!", writer:'Alex' } ] } }) … -
Django MySQL with ElasticSearch
I have a django app. Data is stored in mysql database. There are many tables with many columns (100-200). How can I use Elasticsearch to make search faster? Do I need to rewrite all queries? Links to tutorials will be helpful. -
Django custom form with widget
I am using a custom form (which is not a ModelForm) and I am trying to plug that nicely into the django interface. The issue is that the layout of the form is not the same as a 'regular admin form' and that I can't make the widgets work. I am using: django 1.9 python 3.5 django-selectable django-suit Right now I get correctly the form displayed, but it is not typesetted as another form would be and the autocomplete widget is not working Here is my template code: {% extends "admin/change_form.html" %} {% block field_sets %} {{ form }} {% endblock %} admin.py file: class UsersInEventAdmin(ExportMixin): list_display = ('user', 'event', 'options_selected', 'payed', 'user_phone', 'user_email', 'user_have_certificate') list_filter = ('event__name', 'payed') search_fields = ["^event__name", "^user__user__first_name", "^user__user__last_name"] ordering = ["event__name", "user__user__last_name", "user__user__first_name"] form = SportifInEventAdminForm # Extend for prefilled forms def get_urls(self): urls = super(UsersInEventAdmin, self).get_urls() my_urls = [ url(r'^([0-9]+)/foo/$', self.admin_site.admin_view(self.event_registration_form)) ] return my_urls + urls def event_registration_form(self, request, event): # Populate the options for the event options = [ dict(description=e.description, choices=[(-1, 'Aucun')]+[ (c.id, c.description) for c in EventOptionChoice.objects.filter(option=e) ]) for e in EventOption.objects.filter(event_id=event)] # Parse the request if request.method == 'POST': print('Got a form!') form = UserInEventGenericForm(request.POST, event_options=options) if form.is_valid(): # Save … -
How to put a link to in a django error messages
I want to insert a link to a page inside of my project using the Django error messages something like this messages.error(request, 'Please click <a href="{% url 'myproject:settings' %} >here </a>') -
How to use forms.ChoiceField() inside ModelForm?
I want to show a dropdownlist in my form by using the ModelForm. My code added below- from django import forms from django.forms import ModelForm class CreateUserForm(ModelForm): class Meta: model = User fields = ['name', 'age'] AGE_CHOICES = (('10', '15', '20', '25', '26', '27', '28')) grade = forms.ChoiceField( widget=forms.Select(choices=AGE_CHOICES) ) It's not showing dropdownlist in the form. Also, I want "Select" selected as default with empty value. How can I achieve that? Thanks in advance! -
I want to insert bookmark.title to javascript array
i want to insert bookmark.title to JavaScript array. I tired like photo but it doesn't work. How can i insert bookmark.title to JavaScript array? -
Update Form with Django
I'm creating a function which let to handle forms updating. In my view, user gives an ID, then the script takes this ID and display the corresponding form with the possibility to update data. My function looks like : def Identity_Update(request) : # ID object given by user query_update = request.GET.get('q4') if query_update : updating_form = IdentityForm(request.POST, pk = query_update) # Update form where ID is given by user if updating_form.is_valid() : saving_updating_form = updating_form.save(commit=False) saving_updating_form.save() else : updating_form = None context = { "query_update":query_update, "updating_form" : updating_form } return render(request, 'resume.html', context) My template looks like : <h2 align="center"> Modification des fiches individuelles </align> </h2> {% block content %} <h4> Modifier une fiche individuelle </h4> <form method="GET" action=""> <input type="text" name="q4" placeholder="Entrer un ID" value="{{ request.GET.q4 }}"> <input type="submit" value="Rechercher"> </form> <h3> Modifier les données enregistrées : </h3> <li> Civilité : {{updating_form.title}}</li> <li> Nom : {{updating_form.lastname}}</li> <li> Prénom : {{updating_form.firstname}}</li> <li> Sexe : {{updating_form.sex}}</li> <li> Date de Naissance : {{updating_form.birthday}}</li> <li> Ville de Naissance : {{updating_form.birthcity}}</li> <li> Pays de Naissance : {{updating_form.birthcountry}}</li> <li> Nationalité : {{updating_form.nationality}}</li> <li> Profession : {{updating_form.job}}</li> <li> Adresse : {{updating_form.adress}}</li> <li> Ville : {{updating_form.city}}</li> <li> Code Postal : {{updating_form.zip}}</li> <li> Pays : {{updating_form.country}}</li> <li> Email … -
AJAX GET Document using mongoengine and python django
I'm trying to query MongoDB geojson data using mongoengine in python django. But somehow on trying to attempt on getting an object/document through an AJAX call then converting the found Document using the id passed as data from it to a list to print for debugging purposes, the list returns something like this: ["id", "type", "route_id", "geometry", "properties"] Then I tried to convert it using .to_json still no luck in getting my desired output (the object itself that I could turn into json : with contents) Here's my views.py: def update(request): if request.method == "POST": line = json.loads(request.body) _id = line['_id'] print("Object Id: %s" % (_id.get('$oid'))) route_id = line['route_id'] print("ROUTE_ID: %s" % (route_id)) geometry = line['geometry'] print("GEOMETRIES: %s" % (geometry)) properties = line['properties'] try: Route.objects(id=ObjectId(_id.get('$oid'))).update(set__geometry=geometry, set__properties=properties) print("Edited: " + route_id) save_overwrite_original(request) return HttpResponse("Success!") except: print("Unedited.") return HttpResponse("Error!") elif request.method == "GET": _id = request.GET.get('id','') print("Finding: %s" %(_id)) try: route = Route.objects(id=ObjectId(_id)) route = route.to_json() print(dumps(route)) return HttpResponse(dumps(route)) except: return HttpResponse("Not Found!") and from my js AJAX call: onClick: function(btn){ var editedFeature = selectedFeature.toGeoJSON(); var id = editedFeature._id['$oid']; $.ajax({ url: "/plexus/load-map/update/", type: 'GET', data:{id:id}, success: function(data){ openCreateModal(); alert(data.type) //outputs undefined } }); Although my reason is for update, the actions above … -
Django Logger creates file but doesn't write in it
I am trying to get a Logger working for my Django App. I call the logger with: logger = logging.getLogger(__name__) logger.info("some stuff") inside a function in my views.py. But it doesn't work, the file which is supposed to contain the log is created but nothing is written in it, here are the settings : LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters':{ 'standard': { 'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s' }, }, 'handlers': { 'file_INFO': { 'level': 'INFO', 'class': 'logging.handlers.RotatingFileHandler', 'filename': os.path.join(BASE_DIR, 'logs/site.logs'), 'maxBytes': 1024 * 1024 * 15, # 15MB 'backupCount': 10, 'formatter': 'standard', }, 'console_INFO': { 'level': 'INFO', 'class': 'logging.StreamHandler', } }, 'loggers': { 'INFO': { 'handlers': ['file_INFO', ], 'level': 'INFO', 'propagate': True, }, }, } Any idea ? Thanks ! -
Artificial intelligence for creating my own slack bot
I am creating a slack bot in python using django framework.I need to use artificial intelligence in it. A user can ask a question in different ways and my bot should be able to understand its question. For example a user says in following manner: I want to visit India.Show me some plans of it. I don't want to visit USA. But want to visit India. Please show me some plans of it. I want to visit USA, and indiaaa. How can I make my bot to understand every way of asking question including spelling mistakes.Should I use any AI library or do i need to create my own library for this. Any help would be appreciated. -
Django Contact Form Attachment showing 'This field is required.' What am I doing Wrong?
Views.py from django.conf import settings from django.core.mail import EmailMessage,send_mail, BadHeaderError from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, redirect from .forms import ContactForm def email(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] name = form.cleaned_data['name'] phone = form.cleaned_data['phone'] image1 = request.FILES['image1'] full_message = str([from_email,name.upper(), phone, message]) try: email = EmailMessage(subject.upper(),full_message,from_email+'<sender@gmail.com>',['pratirup8@gmail.com'],headers = {'Reply-To': from_email }) email.attach(image1.name, image1.read(), image1.content_type) email.send() except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('success') return render(request, "email.html", {'form': form}) def success(request): return HttpResponse('Success! Thank you for your message.') Forms.py from django import forms class ContactForm(forms.Form): name = forms.CharField(required=True) phone = forms.CharField(required=True) from_email = forms.EmailField(required=True) subject = forms.CharField(required=True) message = forms.CharField(widget=forms.Textarea, required=True) image1 = forms.Field(label='sample photo', widget = forms.FileInput, required = True ) If I send the mail with out attachment its working but when i add an attachment file it shows "This field is required." in the webpagethis image is a screenshot of the problem i want to know what am doing wrong and how can i send and mail with the attachment -
Celery: form has no len()
I have updated my python versions and celery versions, and now it is not possible to create a task from a form submit: Python==3.4. Django==1.10.3 celery==4.0.0 My view: class SignupBase(FormView): def get_form_class(self, **kwargs): return SignupFormBase def form_valid(self, form): user = User(username=generate_random_username()) user.save() signuptask = signup_user.delay(username=user.username,form=form) The traceback when submitting: Traceback: File “/home/USER/Env/DOMAIN/lib/python3.4/site-packages/django/core/handlers/exception.py” in inner 39. response = get_response(request) File “/home/USER/Env/DOMAIN/lib/python3.4/site-packages/django/core/handlers/base.py” in _legacy_get_response 249. response = self._get_response(request) File “/home/USER/Env/DOMAIN/lib/python3.4/site-packages/django/core/handlers/base.py” in _get_response 187. response = self.process_exception_by_middleware(e, request) File “/home/USER/Env/DOMAIN/lib/python3.4/site-packages/django/core/handlers/base.py” in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File “/home/USER/Env/DOMAIN/lib/python3.4/site-packages/django/views/generic/base.py” in view 68. return self.dispatch(request, *args, **kwargs) File “/home/USER/Env/DOMAIN/lib/python3.4/site-packages/django/views/decorators/cache.py” in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File “./apps/signup/views.py” in dispatch 203. return super(SignupBase, self).dispatch(request, *args, **kwargs) File “/home/USER/Env/DOMAIN/lib/python3.4/site-packages/django/views/generic/base.py” in dispatch 88. return handler(request, *args, **kwargs) File “/home/USER/Env/DOMAIN/lib/python3.4/site-packages/django/views/generic/edit.py” in post 183. return self.form_valid(form) File “./apps/signup/views.py” in form_valid 448. signuptask = signup_user_locally.delay(username=user.username, form=form) File “/home/USER/Env/DOMAIN/lib/python3.4/site-packages/celery/app/task.py” in delay 413. return self.apply_async(args, kwargs) File “/home/USER/Env/DOMAIN/lib/python3.4/site-packages/celery/app/task.py” in apply_async 536. **options File “/home/USER/Env/DOMAIN/lib/python3.4/site-packages/celery/app/base.py” in send_task 709. root_id, parent_id, shadow, chain, File “/home/USER/Env/DOMAIN/lib/python3.4/site-packages/celery/app/amqp.py” in as_task_v2 335. kwargsrepr = saferepr(kwargs, self.kwargsrepr_maxsize) File “/home/USER/Env/DOMAIN/lib/python3.4/site-packages/celery/utils/saferepr.py” in saferepr 74. o, maxlen=maxlen, maxlevels=maxlevels, seen=seen File “/home/USER/Env/DOMAIN/lib/python3.4/site-packages/celery/utils/saferepr.py” in _saferepr 104. for token, it in reprstream(stack, seen=seen, maxlevels=maxlevels): File “/home/USER/Env/DOMAIN/lib/python3.4/site-packages/celery/utils/saferepr.py” in reprstream 155. for val in … -
Django Rest Framework: retrieve object or create object
In my API I'm trying to build endpoints where dataobjects are retrieved if they exists and created if they don't exists. Question: How can I create this functionality in a single view using DjangoRestFramework's generic views? What I'm looking for is basically a RetriveCreateAPIView, but it does not exist.