Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Could not parse the remainder: '{{' from '{{'
I'm trying to create a simple page, which should display a table. It suppose to have several rows and columns. But not every row should have the same amount of columns. this my html code which is producing an error: <html> {% for count in machine_count %} <tr> <td>{{ count }}</td> <td>Aufzugmotor</td> {% for status in statuses %} {{ status.machine_number}} {% if count == {{ status.machine_number }} %} <td class="tableCell"> <img class="imageClass" src={{ status.src }}> </td> {% endif %} {% endfor %} </tr> {% endfor %} </html> statuses is a model and machine_number is a tuple of strings. I'm not really getting the mistake I made. Is it not possible to use the if-tag on a placeholder ? -
Django MySQL fail to get the last state of my db
I’m currently working on a Django 1.11 project where I have two models Profile and Campaign, the first one inlines the second. I want to apply a asynchronous function when I save my Profile. So to do that I create a celery task. # in admin.py class ProfileAdmin(admin.ModelAdmin): # some stuff def save_related(self, request, form, formsets, change): print(“before save: ” + str(len(campaigns))) super(type(self), self).save_related(request, form, fomsets, change) campaigns = Campaign.objects.filter(is_enabled=True) print(“after save: ” + str(len(campaigns))) tasks.foo.delay() # in tasks.py @shared_task def foo(): campaigns = Campaign.objects.filter(is_enabled=True) print(“Foo: ” + str(len(campaigns))) My issue is that the length of the campaigns in foo is the length print before the save and not after. This issue disappear when I add a sleep at the beginning of foo. Example output: before save: 5 after save: 3 Foo: 5 This issue exist only on my google instance with mysql 5.7. I don’t understand why the campaign is not always correct in foo. I doesn’t find any reason to explain this behavior. -
Eclipse pydev, djnago issue
i was exploring Eclipse pydevPlugin with python and Django and found few issue not sure if i am missing something. I am not sure if this is understanding issue of plugin. Please find attached issue screen List item enter image description hereInfo: OS:MAcOS Sierra Eclipse : Eclipse Java EE IDE for Web Developers. Version: Neon.3 Release (4.6.3) Build id: 20170314-1500 Pydev Plugin : 5.7.0.201704111357 Python Django ver : 1.11 Python 3.6 Please find attached Pydev issues: 1. Creating extra folder same name as project( nested names) 2. Could not run this command in consoles django-admin startproject mysite or django-admin startapp mysite ( print(django.get_version()) can be run without any issue) 3. Some file missing when djnago project is created i.e models.py, views.py etc.. as shown in attached file ( Missing files are created when used command - "django-admin startapp mysite") Thanks Kind Regards raky -
Getting month name on Django template from timezone.localtime()
Im trying to display the month name of the datetime object on a django template. This is how Im sending the date: { .. 'today': timezone.localtime(timezone.now()) .. } On the template Im doing this: {{ today|date:"F" }} However Im only getting and empty blank space where whe month name should be. Can anyone help me correct my error? -
Showing multiple values of an object in a Django ModelChoiceField
I have a form that queries my database like so: class Pull(forms.Form): select = forms.ModelChoiceField(queryset=OrderEntry.objects.values_list ('val_a', 'val_b'), required=True) By default, it will show the values, but it's really ugly and not fun to look at. On the webpage it looks something like this in the drop-down menu: ('A','B') ('C','D') I want it to look something like this: A | B C | D Or really, anyway that would be easy for a user to read. Is there a way I can achieve this? Thanks! -
Accessing fields from an model associated to a django user in template
I have a model User_Details associated with each Django User. It has a field named mobile_number. I want to access the mobile_number in my template. I am trying request.user.User_Details.mobile_number but it's not working. Is it the right way? If not, then how should I go about it? -
Django-Private-Chat asyncio server freezes when i run it
I am trying to use django-private-chat's example project but when i run python manage.py run_chat_server it freezes the command prompt like this even ctrl+c doesn't work I am following the tutorial provided on their repo and i changed the chat ws server host and port to this CHAT_WS_SERVER_HOST = '127.0.0.1' CHAT_WS_SERVER_PORT = 8000 i am using python 3.4 on windows 7. any kind of help is really appreciated. -
What is the correct workflow to add migrations to a standalone django app?
Let's say i'm working on a Pull Request for an django app. I've made some changes to the model and now i want to submit my Pull Request. Since i've made changes to the models i also need to submit new migrations. So what is you strategy to create new migrations to your changed models when it is not park of an existing project? I know about the makemigrations command but for this command i need to setup a new virtialenv, a new django project and install all dependencies. Or am i missing something? -
Django - Ajax call OK but python method not called
I'm trying to make an Ajax POST call on a django method in views.py, my ajax called is ok : Ajax call 200 The problem is that my method get_elem in views.py is not called, when I use debugger on that method the process doesn't stop on the breakpoints. (using Pycharm). My ajax call is : function call_elem(elem_id, elem_type) { function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajax({ url : "get_elem/", beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } }, type:'POST', dataType :'json', data : { elem_id : elem_id, elem_typ : elem_type } }).done( function (data) { console.log(data); console.log('Success !'); }); } As you can see, I already have the csrf token from the cookie. The method in views.py is : def get_elem(request): if request.method == "GET": if request.POST.get('elem_id') and request.POST.get('elem_type'): elem_id = request.POST.get('elem_id') elem_type = request.POST.get('elem_type') if elem_type == 'GR' or elem_type == 'GRC': elem = Groupe.objects.get(elem_id) json.dumps(elem.__dict__) else: elem = {"error":"error..."} return JsonResponse(elem) But instead of returning the element in JSON, I get as answer the HTML code of the page from where I'm making the ajax call. I've already done an ajax call previously in … -
Creating a Hierarchy View in Django
I'm trying to create a hierarchy view in Django, but I'm struggling to make sense of how to use QuerySets effectively. What I'm aiming for eventually is a html page that displays courses like this: Main Course 1 --- Child Course 1 --- Child Course 2 Main Course 2 --- Child Course 3 --- Child Course 4 Each group of courses would be wrapped in a div and styled etc. In my view.py file I have the following: class HierarchyView(generic.ListView): template_name = 'curriculum/hierarchy.html' def get_queryset(self): return Offering.objects.all() def get_context_data(self, **kwargs): context = super(HierarchyView, self).get_context_data(**kwargs) context['main'] = self.get_queryset().filter(course_type='M') context['sub'] = self.get_queryset().filter(parent_code__in=context['main']) return context The Offering model is set up so that parent_code is a self-referential foreign key (i.e. any course can be a child of any other), like this: ... parent_code = models.ForeignKey( 'self', null=True, blank=True, on_delete=models.SET_NULL) ... And in my html template I have: {% for mainoffering in main %} <div> <div>{{ mainoffering.course_name }}</div> {% for offering in sub %} <div>{{ offering.course_name }}</div> {% endfor %} </div> {% endfor %} What this results in, however, is that all child courses appear under all main courses, regardless of whether or not they are actually children of that course, which is obviously … -
set a Boolean when submitted in django
I want to set a Boolean field is_rep in a retest model to true when the retest form is submitted. Now it is just get added up in a retest model. Because I want to trigger other events when the request is submitted. My code models.py class Retest(models.Model): semester = models.ForeignKey(Semester) dept = models.ForeignKey(Departement) batch = models.ForeignKey(Batch) date = models.DateField(default=0) subject = models.ForeignKey(Subject) name = models.CharField(max_length=50) admnno = models.CharField(max_length=50) reason = models.CharField(max_length=50) proof = models.CharField(max_length=200) is_hod = models.BooleanField(default=False) is_principal = models.BooleanField(default=False) notify = models.BooleanField(default=False) is_sure = models.BooleanField(default=False) is_rep = models.BooleanField(default=False) def get_absolute_url(self): return reverse( 'retest:retestform') def __str__(self): return self.name urls.py url(r'^retest/retestform/$',login_required(views.RetestCreate.as_view()), name='retestform') views.py class RetestCreate(CreateView): model = Retest fields = ['semester', 'dept', 'batch', 'date', 'subject', 'name', 'admnno', 'reason', 'proof', 'is_sure'] template <form class="form_horizontal" action="" method="post" enctype="multipart/form-data" > {% csrf_token %} {% include 'retest/form-template.html' %} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-success">Submit</button> </div> </div> </form> -
Django Ajax return error messages
How would i return error message with django? I am thinking something like this ( i am using jsonresponse just as an example of how i want to do this): def test(request): if request.method == "POST": if form.is_valid(): form.save return JsonResponse({"message":"Successfully published"}) else: '''here i would like to return error something like:''' return JsonResponse({"success": false, "error": "there was an error"}) else: return JsonResponse({"success}: false, "error": "Request method is not post"}) What I am trying to achieve is to render error messages in template from ajax error function. Something like this: $("#form").on("submit", function(){ $.ajax({url: "url", data: ("#form").serialize, success: function(data){ alert(data.message); }, error: function(data){ alert(data.error); } }); Would that be possible? -
Select rows with a few same parameters
I have 3 tables: Student(id, username), Skill(id, value) and StudentSkill(id, student_id, skill_id). In django models it loooks like that (short version): class Student(models.Model): username = models.CharField(max_length = 50, unique = True) class Skill(models.Model): value = models.CharField(max_length = 50, unique = True) class StudentSkill(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) skill = models.ForeignKey(Skill, on_delete=models.CASCADE) I need write request, which return queryset of students, which have a specific skills. For example, I have next data in database: Student id | username ------ | ------ 1 | user1 2 | user2 3 | user3 Skill id | value ------ | ------ 1 | s1 2 | s2 3 | s3 StudentSkill id | student_id | skill_id ------ | ---------- | -------- 1 | 1 | 1 2 | 2 | 1 3 | 2 | 2 4 | 3 | 1 5 | 3 | 2 6 | 3 | 3 user1 has 1 skill: (s1) user2 has 2 skills: (s1 and s2) user3 has 3 skills: (s1, s2 and s3) If I need take students, which have s1 and s2, I must to take user2 and user3 If s1 --> user1, user2 and user3 If s2 --> user2 and user3 If s1 and s3 … -
Is Django changing my url regex?
I have created the following url in Django. My goal is to match and capture an integer of any length as myvar. urlpatterns = [ url(r'^load/(?P<myvar>[0-9]+)/$', views.home, name='home_with_load') ] When I go to http://localhost/load/5 (a single digit number integer), I am taken to the expected view. However, when I go to the url http://localhost/load/54 (a two-digit integer), I am brought to the django error debug page, which shows that I failed to match this pattern: ^load/(?P<myvar>[0-9])/$ [name='home_with_load'] Note that the + that should follow the [0-9] has disappeared. That explains why my two-digit integer is failing to match. Why did the + disappear? Notes: I get the same result when using \d+. It turns into just \d. I have made sure to kill and restart django to ensure my url regex is recompiled. I've made meaningless changes (like changing the name of myvar) and confirmed that they take affect and show on the error debug page. -
Redirect to the same view after update,delete in Django
How can I redirect to the same view after I deleted object and pass some success message? html: <form action="{% url 'lamp-delete' lamp.id %}" method="post" style="display: inline;"> {% csrf_token %} <input type="hidden" name="product_id" value="{{ lamp.id }}" /> <button type="submit" class="btn btn-outline-danger btn-sm"> <i class="fa fa-trash" aria-hidden="true"></i> </button> </form> views.py def index(request): lamps = Lamp.objects.all() return render(request, 'index.html', {'lamps': lamps}) def productlist(request, categ): MEDIA_URL = settings.MEDIA_URL lamps = Lamp.objects.filter(category=categ) return render(request, 'productlist.html', {'lamps': lamps, 'MEDIA_URL': MEDIA_URL}) class LampDelete(DeleteView): model = Lamp success_url = reverse_lazy('index') urls.py urlpatterns =[ url(r'^$', views.index, name='index'), url(r'^productlist/([a-z0-9]+)/$', views.productlist, name='productlist'), url(r'^accounts/', include('allauth.urls')), url(r'productlist/(?P<pk>[0-9]+)/delete/$', views.LampDelete.as_view(), name='lamp-delete'), ] I'm using django.views.generic.edit and now after successful deleting item using reverse_lazy I can redirect to static page, but I'm trying to overload the existing model and pass some variable with string to this view 'productlist'. If somebody could provide an example I would be very thankful. -
PythonAnyWhere The SECRET_KEY setting must not be empty
So I want to deploy my website on pythonanywhere. I created virtualenv, installed Django and all the apps that I need for my website. I created new app and connected it with my project that I cloned from GitHub. Here is a screenshot of the setting in my web app: My project structure looks like this: My settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ADMIN_ENABLED = False ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'taggit', 'blog', 'widget_tweaks', 'ckeditor', 'ckeditor_uploader', 'user_account', 'captcha', 'mptt', ] SITE_ID = 1 MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'blog_project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'blog_project.wsgi.application' # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases """ # Use this for testing on local pc DATABASES … -
How to get currently logged user in class-based view?
I have class-based view: class AddView(CreateView): model = MyModel fields = '__all__' MyModel: from django.contrib.auth.models import User class MyModel(models.Model): user = models.ForeignKey(User) I'd like to automatically set currently logged user into field 'user' whenever new record is added. How can I do that ? -
Django Admin Action Confirmation Page
In my Django project I have an admin action which requires an confirmation page. I oriented it on the delete_selected action, but it does not work. Here is what I have. part of my admin.py def my_action(modeladmin, request, queryset): if request.POST.get('post'): print "Performing action" # action code here return None else: return TemplateResponse(request, "admin/my_action_confirmation.html") admin/my_action_confirmation.html <form action="" method="post">{% csrf_token %} <div> <input type="hidden" name="post" value="yes" /> <input type="hidden" name="action" value="my_action" /> <input type="submit" value="Confirm" /> </div> </form> This works almost. I get to the confirmation page but if I click "confirm" I just get back to the original page. The part with the action code is never reached. In fact the my_action function isn't called a second time. So how do I tell django, that the my_action function should be called a second time, once I clicked confirm? -
Ajax request and python paypal package and django
I be using https://github.com/paypal/PayPal-Python-SDK to make payments. My code: def enviar_pagamento(request): dados = {'sucesso': False, 'mensagem': ''} if not request.session.get('pedido_id'): return HttpResponse(json.dumps(dados), 'application/json', status=200) pedido = Pedido.objects.get(pk=request.session['pedido_id']) paypalrestsdk.configure({ "mode": settings.MODE_PAYPAL, "client_id": settings.CLIENT_ID, "client_secret": settings.CLIENT_SECRET_PAYPAL }) dados_cartao = { "type":'visa', "number": 'xxxxx', "expire_month": xxx, "expire_year": xxx, "cvv2": 'xx', "first_name": 'xxx', "last_name": 'xxx' } reservas = [...] payment = paypalrestsdk.Payment({ "intent": "sale", "payer": { "payment_method": "credit_card", "funding_instruments": [{ "credit_card": dados_cartao}]}, "transactions": [{ "item_list": { "items": reservas}, "amount": { "total": "{0}".format(pedido.valor), "currency": "USD"}, "description": pedido.evento.atracao.nome}] }) if payment.create(): dados['mensagem'] = "Pagamento efetuado com sucesso" dados['sucesso'] = True return HttpResponse(json.dumps(dados), 'application/json', status=200) dados['mensagem'] = "error" print(payment.error) return HttpResponse(json.dumps(dados), 'application/json', status=200) The payment is created but the ajax response ever is canceled and my django server show broken pipe. Some idea to help-me? -
Django, external link url amended to project url
I have a Django project and want to take the user to an external link in openstreetmaps that is supplied lat and long from my Django model. In my view, I develop a url like this: "http://www.openstreetmap.org/?minlon=-92.024&minlat=57.5129102&maxlon=-91.52&maxlat=43.00&mlat=42.899&mlon=-91.774" and I provide it as a variable in my template. The link in my template is: <a id="map" target="_blank" href={{mapurl}}>map</a>. {{mapurl}} is the url fed from my view. The problem is that Django tries to find a url conf that looks like: http://127.0.0.1:8000/beach/1825108/%22http://www.openstreetmap.org/?minlon=-92.0240039&minlat=42.78940921&maxlon=-91.5240039&maxlat=43.00940921&mlat=42.89940921&mlon=-91.7740039%22 rather than taking the user to the openstreetmap in a new page. Any thoughts? -
Django get foreign key object inside Queryset
I have 3 models: class Event(models.Model): cur_datetime = models.DateTimeField(default=datetime.datetime(1970, 1, 1, 0, 0, 0, 0, pytz.UTC), blank=True, null=True) week_no = models.IntegerField() day_no = models.IntegerField() class SubEvent(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE) version = models.IntegerField() class SubSubEvent(models.Model): sub_event = models.ForeignKey(SubEvent, on_delete=models.CASCADE) length = models.IntegerField() I want to get a Queryset from SubSubEvent model, which includes all the Foreign keys as one single object. What I have now is: querySet = SubSubEvent.objects.filter(sub_event__event__cur_datetime__range=[from_date, to_date]) This will return a queryset, and using a for loop to get __dict__ on each of objects, I get something like this: {'event_id': 1, '_state': <django.db.models.base.ModelState object at 0x7fd7d9cefeb8>, 'id': 10, 'length': '1'} This is just a part of the query I want to achieve. What I really want, is all the fields in event_id instead of just the id number. In other word, all the fields (including data) from Event plus SubEvent plus SubSubEvent in one queryset. This queryset should contains objects with cur_datetime, week_no, day_no, version and length. -
Access Django from outside
I installed Django on my Ubuntu Server 14 as a development tool. I want to access Django outside my server by using the URL http://my_server_ip:82 on any computer. So I ran the command python manage.py runserver 0.0.0.0:82. But when I try to connect to http://my_server_ip:82 from another computer, it doesn't work.. I also : - allowed port 82 by using ufw allow in 82 and ufw allow out 82. - wrote ALLOWED_HOSTS = ['*'] in settings.py I read many and many topics dealing with this problem but it finally worked in many cases. I tried everything but nothing seems to work.. Would you have any solutions ? Thanks ! -
Server Error 500 Django Digital Ocean
i've deployed my django project in digital ocean, I'm getting Server Error(500), however the url is showing me myipaddress/accounts/login/?next=/ . I could n't figure out what is causing error. I've kept DEBUG=False even in settings.py -
How to return two values for two foreign keys in same model separately?
class student(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) class details(models.Model): first_name = models.ForeignKey(student,models.DO_NOTHING, db_column='first name', blank=True, null=True) last_name = models.ForeignKey(student,models.DO_NOTHING, db_column='second name', blank=True, null=True) while displaying the details model in template this first_name and last name will be displayed as drop downs.The values in dropdowns will be displayed like "studentObject" and "studentObject" but i want to display then value first name and second name in drop downs.. please help me out. -
CircleCI 4G memory breach - Django migrations
We are using circleci for our Django/Python project. While the test database is being setup as part of TransactionTestCase, the memory shoots up to ~3g and hence breaching the 4g limit of our circle ci environment. I debugged using ssh and found that some tests run in parallel where the 4g limit is breached and hence circle ci build fails. Is there a good way to reduce the memory footprint while setting up databases for tests? Any help will be greatly appreciated!