Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Print dict in template
I've a dict defined as: defaultdict(<class 'collections.Counter'>,{ 'product1': Counter({'total_qty': 1}), 'product2': Counter({'total_qty': 13}), 'product3': Counter({'total_qty': 65}) }) I pass it to the template with: context = {'my_dict': my_dict} return render(request, 'components_by_season.html', context) In the template I try to print it without any luck: <ul> {% for k,v in my_dict.items %} <li>{{ k }}: {{ v }}</li> {% endfor %} </ul> what am I doing wrong? -
Bootstrap Modal in Django application with Ajax
I have little problem in my Django application. I am tring to use modal from bootstrap 4 and ajax to create new object. Here below you see code that I used. When user click the button I dont see modal window but background became grey. What I did wrong? Why I dont see modal? Is my ajax correct? detail.html: <!-- BUTTON TO TRIGGER THE ACTION --> <button class="add-group-task" data-toggle="modal" data-target="#add-group-task-modal" data-url="{% url 'project:group_task_add' project_code=project.code %}">{% trans 'Create' %}</button> <table class="table table-bordered" id="group-tasks-table"> <!-- TABLE CONTENT--> </table> <!--MODAL--> <div class="modal fade" id="add-group-task-modal" tabindex="-1" role="dialog" aria-labelledby="add-group-task-modal-title" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> </div> </div> </div> urls.py: url(r'^(?P<project_code>[0-9a-f-]+)/add_new_group_task/$', group_task_add, name='group_task_add'), view.py: def group_task_add(request, project_code): data = dict() project = get_object_or_404(Project, pk=project_code) if request.method == 'POST': form = GroupTaskAddForm(request.POST) if form.is_valid(): group_task = form.save(commit=False) group_task.project = project group_task.save() data['form_is_valid'] = True group_tasks = GroupTask.objects.filter(project=project_code) data['html_group_tasks'] = render_to_string('project/project_detail.html', {'group_tasks': group_tasks}) else: data['form_is_valid'] = False else: form = GroupTaskAddForm() context = {'form': form} data['html_group_task_add_form'] = render_to_string('project/group_task_add.html', context, request=request) return JsonResponse(data) javascript: $(function () { /* Functions */ var loadForm = function () { var btn = $(this); $.ajax({ url: btn.attr("data-url"), type: 'get', dataType: 'json', beforeSend: function () { $("#add-group-task-modal").modal("show"); }, success: function (data) { $("#add-group-task-modal .modal-content").html(data.html_form); … -
How to visit other user profil Django
So I want that user view other user profil and their posts without editing them. And I hve some trouble doing it. In the view I have something like this: def Profil(request): if not request.user.is_authenticated(): return render(request, 'blog/visitor.html') else: posts = Post.objects.filter(user=request.user) return render(request, 'blog/profil.html', {'posts': posts}) And here the index.html where a user click on another user to view his profil. <a href="{% url 'blog:profil' %}">{{post.user.username }}</a> An my url.py looks like this: url(r'^profil/$', views.Profil, name = 'profil'), Thanks ! -
Use Docker to compile and run untrusted code in Django App
I am building a Django web application to compile and run untrusted code in different languages submitted by user. The steps behind compilation are : Take the code from editor provided on run action store in database with a file name run it using bash script. Since there are problems of security, of directly running code in terminal, I have thought to use Docker as a solution. i have created a docker file as shown below: FROM chug/ubuntu14.04x64 # Update the repository sources list RUN echo "deb http://archive.ubuntu.com/ubuntu trusty main universe" > /etc/apt/sources.list RUN apt-get update #RUN apt-get upgrade #Install all the languages/compilers we are supporting. RUN apt-get install -y gcc RUN apt-get install -y g++ RUN apt-get install -y python I am hoping to build containers for each code run by user and destroy them after use. but how exactly do i create containers on each code run and delete them? I am completely new at docker. Please help me . If Docker is not a good idea, how do i make the editor more secure and terminate on system commands for different languages? -
Interface R with Django
I'm new to Django and want to interface R with it. I want my R scripts to run on the different datasets provided by Django users. How can I achieve it? -
Request.session Djnago not working
I have a basic login page once you log in it redirects you to another app index.html. I want it to set a request.session.name to the page based off the person that logged in However it just comes up blank. I have read though the documentation and I do have everything setup right and I have done .name instead of ['name'] being that it is in html. I do have foreign keys setup and the name is coming from the main table. Looking though how many times this has been answered on stack I was unable to find the solution to the issue im having. Seems to be right but obviously I am missing something. Html <h1>Welcome {{ request.session.name }}!</h1> veiw.py index section def index(request): context = { 'info':Myblackbelt.objects.filter() } print(Myblackbelt.objects.all()) return render(request, 'blackbeltapp/index.html', context) models for the login app class User(models.Model): name = models.CharField(max_length = 100) username = models.CharField(max_length = 50) datehired = models.CharField(max_length = 50) password = models.CharField(max_length =100) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) objects = UserManager() models for the blackbelt app class Myblackbelt(models.Model): product = models.CharField(max_length = 70) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) loguser = models.ManyToManyField(User, related_name='loguser') … -
Django celery/any Worker on separate machine
Inside django app request, I want to send tasks to rabbitmq broker (running on different machine) Then from the rabbitmq I need to run the tasks. (like kafka consumers) Note: I don't want to run the celery workers inside where my webserver is running. How can I run the workers on separate machine and getting the tasks from rabbitmq ? how can I call asyn_func inside request scope to send put the task to rabbitmq broker ? -
How to save mutilate radio button choices as same database object
I've restarted my application due to it being a big mess. Currently i have my models.py layout like so (this is so that each indivitual question has radio buttons) Models.py question1 = models.CharField(max_length=1, choices=Question1_CHOICES) question2 = models.CharField(max_length=1, choices=Question2_CHOICES) question3 = models.CharField(max_length=1, choices=Question3_CHOICES) question4 = models.CharField(max_length=1, choices=Question4_CHOICES) question5 = models.CharField(max_length=1, choices=Question5_CHOICES) question6 = models.CharField(max_length=1, choices=Question6_CHOICES) question7 = models.CharField(max_length=1, choices=Question7_CHOICES) question8 = models.CharField(max_length=1, choices=Question8_CHOICES) question9 = models.CharField(max_length=1, choices=Question9_CHOICES) question10 = models.CharField(max_length=1, choices=Question10_CHOICES) I wanted to know when I do form.save in my views.py how can I get this all to save in the same column Forms.py class Meta: model = Question fields = ['name', 'question1', 'question2', 'question3', 'question4', 'question5', 'question6', 'question7', 'question8', 'question9', 'question10', ] I've tried to compact the models down by combining the _CHOICES option under a single CharField but this causes issues when its show in HTML as it will only display Question10 and none before it. -
Django - restrict users from getting access to same value
I have a calendar which is suppose to be connected to the current admins-association. Admin picks a date in the calendar and register the form so that event is set. But when i log in with another admins-association, i still can see the event from the last admin. I want to keep them separately from each other. Still a newbie so guide me in the right way and appreciate all your help, folks! models.py class Administrator(AbstractUser): ... association = models.ForeignKey(Association) class Event(models.Model): ... association = models.ForeignKey(Association) class Association(models.Model): asoc_name = models.CharField(max_length=50, null=True, blank=True) views.py class calendar(ListView): model = Event template_name = 'calapp/calendar.html' def get_queryset(self): queryset = Event.objects.filter(association=self.request.user.association) return queryset def event_add_edit(request): if request.method == 'POST': res = {'success': False} action = request.POST['action'] name = request.POST['name'] location = request.POST['location'] start = request.POST['start'] end = request.POST['end'] allday = request.POST['allday'] == 'true' description = request.POST['description'] synced = request.POST['synced'] == 'true' association = Association.objects.filter(asoc_name=request.user.association) asoc = Association.objects.get(id=association) if action == 'add': Event.objects.create( name=name, location=location, start=start, end=end, allday=allday, description=description, synced=synced, association=asoc ) res['success'] = True res['message'] = 'added' eid = Event.objects.latest('id').id res['eid'] = eid res['data'] = Event.objects.values().get(id=eid) elif action == 'edit': eid = request.POST['eid'] event = Event.objects.get(id=eid) event.name = name event.location = location event.start = … -
Python Doctest Outputchecker
I trying to run 1 project and receiving strange error when trying to run server or using make commands like $ -u www-data make compilemessages $ -u www-data bin/django collectstatic --noinput or $ ./bin/django runserver I always receiving this error message: class _NonManglingOutputChecker(doctest.OutputChecker): AttributeError: 'module' object has no attribute 'OutputChecker' import doctest import re class _NonManglingOutputChecker(doctest.OutputChecker): Last line witch throws error, how can i solve that? -
How to get Django request.path_info without i18n language code
While having i18n turned on, all the request.path_info contains language. eg: /en/home/. This is a big issue since trying to write LoginRequiredMiddleware gets terribly hard while checking for language in path. And writing it for pages with and without i18n generally since "/en/" url will get treated differently with and without i18n enabled/disabled. Not mentioning that some URL can be without i18n language even in i18n enabled project. Is there any plain path in request? Eg. path stripped correctly in both i18n enabled/disabled projects? -
How to prevent users from editing or deleting other user posts ? Django
Each user has his own posts and he can edit them, but now he can edit other users posts here is my edit_post def post_edit(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = PostForm(request.POST, instance=post) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.published_date = timezone.now() post.save() return HttpResponseRedirect(post.get_absolute_url()) else: form = PostForm(instance=post) return render(request, 'blog/post_form.html', {'form': form}) -
While parsing json and viewing html source code it shows 10K lines
I am parsing json in Django Views with following code: def xyz(request): url =" https://tools.vcommission.com/api/coupons.php?apikey=952d164efe86ca9ec33a1fdac8e6d0b6d4c02c92f44062bf8b646ad04ebf8cdc " response = urllib.request.urlopen(url) data1 = json.loads(response.read()) context = {"data1": data1} template = 'coupons/store/myntra.html' return render(request, template, context) Now I am using this code in my template file {% for item in data1 %} {% if item.offer_id == "1022" %} {{ item.coupon_title }} <br> {% endif %} {% endfor %} All code is working fine but when I view my template html source code it is more than 10K lines. It's taking more time to load. Please suggest some ways. -
Django admin: Show/Hide field on change select any one dropdown field
models.py: class Plan(models.Model): PLAN_TYPE_CHOICES = ( ('global', 'Global'), ('user specific', 'User Specific'), ) name_of_plan = models.CharField(max_length=256, null=False, blank=False) number_of_months = models.IntegerField(db_index=True) type_of_plan = models.CharField(choices=PLAN_TYPE_CHOICES) specific_users = models.ManyToManyField(User, db_index=True) admin.py from django.contrib import admin from .models import Plan class PlanAdmin(admin.ModelAdmin): model = Plan admin.site.register(Plan, PlanAdmin) In admin page I have type_of_plan with choices: "Global", "User Specific"... When I select "User Specific" value I need to show specific_users field And when I select "Global" value I need to hide specific_users field... How can I do it? -
Error after running the command : python manage.py syncdb
I have installed django version 1.5 on python version 2.7 and django non-rel's version 1.5 on my project's virtual environment. Then i have installed mongodb's latest version 3.4 using this command : sudo apt-get install -y mongodb-org. Now when i start mongodb service and then run this command : python manage.py syncdb i get this error[[1]: https://i.stack.imgur.com/26OB7.png][1] -
How to store calculated value in model field in Django?
I want to store two calculated fields in my extended user model Ai and Ei. these are calculated in views. my code is following models. py class User(AbstractUser): Ai = models.TextField(null=True) Ei = models.TextField(null=True) def __str__(self): return self.username and i am calculating Ai and Ei when user goes to link /join/so url.py is url(r'^join/$', views.user_join), In user join view @login_required(login_url='/login/') def user_join(request): #Calculate Ai and Ei from Random User.Ai = str(Ai) User.Ei = str(Ei) User.save() Now my problem is how do I store or Update values of Ai and Ei in the model for particular user -
Flask-socketio instance not Emitting from an External Process (Django)
Hello am trying to emit to flask-socketIO from an external python application (django) but unfortunately it is not emitting. I have defined my flask-socket app as follows: app.register_blueprint(views) socketio.init_app(app, message_queue='redis://127.0.0.1:6380') My views are as follows: from flask import render_template from .. import socketio from App import socketio from App.views import views from flask_socketio import join_room, leave_room, emit import cgi def ack(): print("cron_failedMsg was delivered") @socketio.on('connect', namespace='/node/cron') def ws_conn(): print("Connected") @socketio.on('join', namespace='/node/cron') def on_join(data): print("Joined room " + data['room']) join_room("room_" + data['room']) emit('msg', {'msg': "joined room room_" + data['room']}, room="room_" + data['room']) @socketio.on('leave', namespace='/node/cron') def on_leave(data): print("leaved") leave_room("room_" + data['room']) @socketio.on('cron_failed', namespace='/node/cron') def ws_cron_failed(message): print("Failed") print("sending to room " + message['room']) """ socketio.emit('cron_failed', { 'cron_failed': cgi.escape(message['cron_failed'])}, namespace='/node/cron') """ emit('cron_failedMsg', { 'cron_failed': cgi.escape(message['cron_failed'])}, room="room_" + cgi.escape(message['room'])) Am emitting to the message queue from an external python application (Django): from flask_socketio import SocketIO socketio = SocketIO(message_queue='redis://' + redis6380_conf.redis6380['host'] + ":" + redis6380_conf.redis6380['port']) socketio.emit( 'cron_' + status, {'cron' + status: redisConnection6381.get(str(userID) + '_' + status), 'room': str(userID)}, namespace='/node/cron') Unfortunately its not emitting from the external python process. I've tested emission from a webpage using javascript it works but not from the external python application(Django): var url = "http://" + document.domain + ":" + location.port; … -
Can't get the username id in the url Django
Here is my view.py def Profil (request, username): user = User.objects.get(username=username) return render(request, 'blog/Profilvisitor.html', {}) And here the index.html <a href="{% url 'blog:profil' username %}"> {{post.user.username }}</a> and my url.py url(r'^profil/(?P<username>\w+)/$', views.Profil, name = 'profil') enter image description here Thanks in advance guys ! -
CSRF Failes when testing django using postman
I have a django (rest_framework) application in which i just added some authentication. Creating an account and logging in with the account went well for the first time but then the trouble began. Right now whenever or however i try to register/login/logout i instantly get an error message saying that the csrf verification failed or the token was missing. So i started to find out what it meant and came to the conclusion that it is quite important for authentication. It is unclear to me how i can get the application authentication system working without damaging the security. Can someone explain to me how i can communicate with my application without compromising the csrf token. (for example in Postman) Thanks in advance! My code is pretty standard django auth code authentication = [ url(r'^status/$', StatusView.as_view()), url(r'^register/$', RegisterView.as_view()), url(r'^login/$', LoginView.as_view()), url(r'^logout/$', LogoutView.as_view()), ] --- views.py --------------- class RegisterView(APIView): def post(self, request: Request): acc = authentication.AccountSerializer(data=request.data) helper.validate_serializer(acc) return Response(acc.data) class LoginView(APIView): def post(self, request: Request): username = request.data.get("username", "") password = request.data.get("password", "") user = authenticate(username=username, password=password) if user is not None: login(request, user) return Response({"message": "Login successful", "account": authentication.AccountSerializer(user.account).data}) else: return APIException(detail={"message": "Login unsuccessful"}) class LogoutView(APIView): def post(self, request: Request): logout(request) … -
Rpy2 and Django Error: C stack usage 69077360 is too close to the limit
I am creating a django project in Windows in which i need to call few existing R codes (saved as .R files) via django views functions. To achieve this, I am using rpy2 python library. After including the import statement only (import rpy2.robjects as robjects), Django server crashes with error : Error: C stack usage 69077360 is too close to the limit There are around 30 R scripts, that needs to be sourced through django. I am unable to proceed further. Can anyone please help me resolve the issue on urgent basis ? Snippet of my code : from rest_framework.decorators import api_view from rest_framework.response import Response import rpy2.robjects as robjects @api_view(['GET']) def send_variables(request): try: print(robjects.globalenv.keys()) robjects.r.source("variables.R") result = robjects.r("get_variables()") variables = [] for var in result: variables.append(var) except: message = "Error while processing the request" logger.exception(message) return Response(data=message, status=status.HTTP_400_BAD_REQUEST) return Response(data={"all_variables":variables}, status=status.HTTP_200_OK) Versions being used : OS -Windows 7 64bit, R - 3.3.2, Python- 3.5, Django - 1.10, Rpy2 - 2.8.5 . -
Iterate dictionary in django template
I have a dictionary >>> filterdata {u'data': [{u'filter': u'predictions', u'filtervalue': u'32', u'filterlevel': u'cltv', u'filtertype': u'>'}, {u'filter': u'profile', u'filtervalue': u"'TOMMY'", u'filterlevel': u'firstname', u'filtertype': u'='}]} and i am using this to in django template {% for c in filterdata.data %} {{c}} ## print the current iterating dictionay {% for d in c.items %} {{ d.filtervalue }} ## does not print anything {% endfor %} {% endfor %} any idea what i am doing wrong -
How to add custom-fields (First and Last Name) in django-registration 2.2 (HMAC activation Workflow)?
There are already some question on this but most of their answers are using models based workflow which is not a recommended way anymore according to django-registration. I am just frustrated from last week, trying to figure out how to add first and last name fields in registration form in HMAC Workflow. -
Django - best practice for translating and organizing enumeration-type data structures
Let's consider a model: class MobileContact(models.Model): contact_type = .... So we have to model mobile contacts and each contact has a type (like work number, mobile number, email, fax, pager) etc. At first, I organized the code the following way: class ContactType(ChoiceEnum): mobile = 1 work = 2 home = 3 work_fax = 5 home_fax = 6 email = 7 class MobileContact(models.Model): contact_type_id = models.IntegerField(ContactType.choices()) This approach has an advantage of the following code pattern: contact_values_qs.filter(contact_type_id = ContactType.email.value) This pattern has pros and cons: Pros: Good code readability (contact_type_id = ContactType.email.value is much nicer than contact_type_id = 7) Cons: If I have to see the enumeration values in user interface, I don't have string representations, not to mention inability to translate these strings So I rewrote the code in a standard way: class MobileContact(models.Model): contact_type = models.ForeignKey(ContactType, ...) class ContactType(models.Model): type_name = CharField(...) THE QUESITON: How do I translate the values of type_name? I came across this post, but the latest supported version of python is 3.4. My project deploys 3.5 How do I structure the code when selecting contact_types to maintain code readability. For example, I want to select work and work_fax. The only way I know to do … -
Javascript to conditionally change the form in django
I'm using a simple django form which when the user: 1. clicks on crawl by categories radio button, displays another checkbox set of names like football, sports etc. 2. Or if the user selects crawl by query then a text box should appear. Once user submits it will redirect to another page. I'm not able to do this using conditional logic and i need help to know what im doing wrong. This is my crawl.html <form action="" method="post"> {% csrf_token %} <script src="https://code.jquery.com/jquery-1.12.3.min.js"></script> <script type="text/javascript"> // step 2: run function when clicking radio button $(document).ready(function() { $('#id_selection').on('change',function(){ // step 3: get selected value var selected_value = $('input[id="selection"]:checked').val(); alert(selected_value); // somehow this always gives "undefined value" // step 4: hide/show dive based on selected_value if(selected_value==0){ $("#categories").show() $("#id_crawlSelection").show() $("#query").hide() } else if(selected_value==1){ $("#query").show() $("#categories").hide() } }); }); </script> {{ form.selection }} <div class="span4" id="categories" style="display:auto"> {{ form.crawlSelection }}<br/> </div> <div class="span4" id="query" style="display:auto"> {{ form.query }}<br/> </div> <input type = "SUBMIT" value="Submit" id="submit"> And my forms.py is from django import forms class CrawlForm(forms.Form): OPTIONS = [ (0, 'Crawl by Categories'), (1, 'Crawl by Query'), (2, 'Crawl all') ] selection = forms.ChoiceField(choices=OPTIONS, widget=forms.RadioSelect()) CATEGORIES = [(0, 'Football'), (1, 'Sports') ] crawlSelection = forms.MultipleChoiceField(CATEGORIES, … -
Video sharing website language advice
I want to build a video sharing website like Youtube. Please advice me what programming language or framework I can use it for? Please keep in mind i will be doing a complex search engine analysis for video searching.