Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Having trouble writing loops in django template
Hello guys I am currently working on django views and templates and met some problems. I have a model named 'metabolites', which contains: id, name, compartment, charge and formula 5 components. I have another model named 'Reactionsmeta', which contains: id(reactions), name, metabolie1, metabolite2, .... metabolite6. The table of this model is not filled complete, because sometimes one id corresponds to 5 metabolites, but sometimes even 20. I write a template which can displays all the reaction, when I click on the reaction and enter the detail page, I also want to display the metabolites that involve in this reactions. My views.py and templates are written as below: reactions_detail.html {% extends 'Recon/Base.html' %} {% load static %} {% block title %}Reaction Details{% endblock %} {% block body %} <h1>{{ reactionsmeta.id }}</h1> <h2>{{ reactionsmeta.name}}</h2> <!-- Left Album Info --> <div class="col-sm-4 col-md-3"> <div class="panel panel-default"> <div class="panel-body"> <a href="{% url 'detail_reaction' reactionsmeta.id %}"> {% if reactionsmeta.id %} <img src="{% static "Recon/images/Logo-Technische-Universiteit-Eindhoven.jpg" %}" class="img-responsive"> {% else %} <h3>No image to display</h3> {% endif %} </a> <h1>{{ reactionsmeta.id }} <small>{{ reactionsmeta.name }}</small></h1> </div> </div> </div> views.py from django.views import generic from .models import Reactionsmeta,Metabolites,Reactions from django.shortcuts import render class IndexView(generic.ListView): template_name = 'Recon/index.html' context_object_name … -
How to restart the Django application once the server reboots?
I have deployed Django application with gunicorn + nginx + postgres. I am using digitalocean ubuntu server.Which sometimes once in a month reboots automatically so that application goes down. How to auto restart the application? -
I get the message "No module named django" even after though it is installed and in the system path
I am setting up django on my system using this tutorial, https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/development_environment. I did everything exactly as it told me to, but when I run the command "py -3 -m django --version", I get the message : "C:\Users\Vivek\AppData\Local\Programs\Python\Python36-32\python.exe: No module named django". I checked and the django installation is in the system path, and I can import django in python. What can I do to fix this error? -
Heroku: Couldn't import Django when working with django-oscar
I have a django oscar application and this application is to be deployed on heroku. I have an application running on heroku already so i did the whole process well. initially I had just django available in my heroku project which works fine with heroku migrate but on adding the remaining requiremnts.txt details and pushing to heroku which works fine I get no errors. But the moment I run heroku run python manage.py migrate with the updated applications I get the error File "manage.py", line 17, in <module> "Couldn't import Django. Are you sure it's installed and " 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? of which everything worked well locally and also worked well when I initially migrated with just a blank django project. Any help would be appriciated. Thanks -
Django Html button change color depending on status
The code works fine, but the problem is if the student is taken this week. It change the button to red which i want, but it also display the green button next to it. Which i don't want if the student is booked. {% for student in studentList %} <tr> <td>{{ student.firstname }}</td> <td>{{ student.lastname }}</td> <td>{{ student.parent }}</td> {% for classes in classesList %} {% if student.id == classes.student_id %} <td><button type="button" class="btn btn-danger">not available</button></td> {% endif %} {% endfor %} <td><button type="button" class="btn btn-success">Book Student</button></td> </tr> {% endfor %} -
How to use django-rest-hooks?
I made API using django-rest-framework and now want to add notification function. So, I thought that use this python package(django-rest-hooks). I followed bellow code. ### settings.py ### INSTALLED_APPS = [ # others 'rest_hooks' ] HOOK_EVENTS = { 'payment.changed': 'app_name.Payment.updated+', } ### app_name/models.py ### class Payment(models.Model): user = models.ForeignKey('auth.User') # maybe user is off a related object, so try... # user = property(lambda self: self.intermediary.user) amount = models.IntegerField() # ... other fields here ... def serialize_hook(self, hook): return { 'hook': hook.dict(), 'data': { 'id': self.id, 'amount': self.amount, # ... other fields here ... } } But I can't feel any change and notification. How to use this package? -
How to mock redis for Django tests
I am trying to mock out redis in my Django application. I have tried several different methods but none seem to work. What am I doing wrong? My primary redis instance is called with: redis_client = redis.from_url(os.environ.get("REDIS_URL")) That instance is imported in other parts of the app in order to add and retrieve data. In my tests I tried doing: import fakeredis from mock import patch class TestViews(TestCase): def setUp(self): redis_patcher = patch('redis.Redis', fakeredis.FakeRedis) self.redis = redis_patcher.start() self.redis.set('UPDATE', 'Spring') print(redis_client.get('UPDATE')) def tearDown(self): self.redis_patcher.stop When running the tests I want the 'UPDATE' variable to be set. But instead every instance of redis_client fails saying the server is not available. How can I mock out redis and set values, so that they are available when testing my app? -
Unexpected token P in JSON at position 0 when trying to return Excel spreadhsheet
I have an emberJS application where I can make a POST AJAX call to a Django backend. A function in Django creates an xlsx file for a bunch of queried items based on IDs coming in the POST request. It goes through the Django view function without any issues, but when the HTTP response is returned to ember, I get the error SyntaxError: Unexpected token P in JSON at position 0 at parse (<anonymous>) at ajaxConvert (jquery.js:8787) at done (jquery.js:9255) at XMLHttpRequest.<anonymous> (jquery.js:9548) at XMLHttpRequest.nrWrapper (base-content:20) I'm setting the response content type to application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, so I'm unsure as to why its trying to read the response as JSON. Python Code file_path = '/User/path_to_spreadsheet/content.xlsx' fsock = open(file_path, "rb") response = HttpResponse(fsock, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename="content.xlsx"' return response EmberJS Code export default Controller.extend({ actions: { storeProductId(products) { let product_ids = [] products.forEach(function(product){ product_ids.push(product.id) }); let adapter = this.store.adapterFor('product-export'); adapter.export_products(product_ids).then(function(response){ console.log(response) }).catch(function(response) { console.log('ERROR') console.log(response) }) } } }); -
Clearing celery back-end result data
I have a django project with celery library integrated. How can I clear my celery back-end result data? I am using django-db as my celery worker backend. CELERY_RESULT_BACKEND = 'django-db' -
Django function parse_duration() cannot parse years or months
I am trying to parse the ISO 8601 duration P1Y or P1M, representing one year or one month respectively, using the parse_duration() function of the django.utils.dateparse module. The returned value though is None. The documentation of the function says that it supports ISO 8601 durations. But it seems that it supports the standard without the years or months, because I can successfully parse the duration P2DT12H60M33S, resulting in a timedelta object of 2 days and 46833 seconds. Is this a bug, a feature or am I doing something wrong? -
Set the ForeignKey to value in field of self in Django 2.0 and Python
I'm perhaps a little confused as to how ForiegnKey and database relationships work. I have two classes, Coin contains a list of items coin names. CoinData rows of data, containing daily price data for each coin. I want each CoinData to be ForiegnKey tied to their matching item in Coin, and to do this I gave CoinData a 'coin' ForeignKey attribute to my Coin model but all this does is produce a field of 'Coin' options on each CoinData item. I want to programmatically assign the value in coin_name, to the Coin object it matches with on each row of data. Am I going about this the right way, or am I doing things wrong? class Coin(models.Model): """ A class defining all the coins we'll have on the website """ # Fields name = models.CharField(max_length=30, unique=True, help_text="Enter coin name") class CoinData(models.Model): """ A class defining the daily coin data """ # Fields coin_name = models.CharField(max_length=30, null=True, default='empty') coin = models.ForeignKey(Coin, on_delete=models.SET_NULL, null=True) date = models.DateField(null=True, blank=True) open_price = models.DecimalField(max_digits=30, decimal_places=10, null=True, help_text="Opening Price") high_price = models.DecimalField(max_digits=30, decimal_places=10, null=True, help_text="High Price") low_price = models.DecimalField(max_digits=30, decimal_places=10, null=True, help_text="Low Price") close_price = models.DecimalField(max_digits=30, decimal_places=10, null=True, help_text="Low Price") volume = models.DecimalField(max_digits=30, decimal_places=10, null=True, help_text="Volume") … -
Django Channels database_sync_to_async QuerySet results
class MyConsumer(AsyncIrcConsumer): @staticmethod @database_sync_to_async def fetch_component(command): return Component.objects.filter( type__slug=TYPE_SLUG name=command ) @staticmethod @database_sync_to_async def fetch_component_2(command): return Component.objects.get( type__slug=TYPE_SLUG, name=command ) @staticmethod @database_sync_to_async def fetch_component_3(command): return Component.objects.filter( type__slug=TYPE_SLUG name=command )[0] >>> components = await MyConsumer.fetch_component("cmd") >>> components QuerySet[<Component>] >>> component = await MyConsumer.fetch_component_2("cmd") campaigns.models.DoesNotExist: Component matching query does not exist. >>> component = await MyConsumer.fetch_component_3("cmd") >>> component is None True So it is most likely that I am confused about the sync/async relationship and making an obvious mistake. My expectation based on the limited docs I've located lead me to believe that the three methods above should be equivalent, yet clearly they behave differently. I'd like to get 1 Component which (through other means I've ensured) is unique and exists. An ideal answer explains the distinction here. -
Django HTML display foreign key name
How can i make it display the key name of the owner? I was only able to figure out to display the id of the owner, since it's a foreign key {% for pet in petList %} <tr> <td>{{ pet.name }}</td> <td>{{ pet.breed}}</td> <td>{{ pet.owner_id }}</td> </tr> {% endfor %} In the admin panel it shows the owner name, but when i try to display in html, i'm only able to show the id. -
Django ModelChoiceField - Select a valid choice error
Context: Creating a form in Django so users can select a single object from the database which they can then go on to write a review about. When submitting the form, I get the error "Select a valid choice. That choice is not one of the available choices". Current Code: At the moment, I am using a for loop in my template to iterate over each object from the queryset. I am doing it this way since I want to customise different aspects of the list of objects (style and information). forms.py: class ProductSelectForm(forms.ModelForm): related_obj = forms.ModelChoiceField(queryset=Product.objects.all(),required=True,empty_label=None,widget=forms.widgets.RadioSelect(attrs={'class':'radio-styled'})) def __init__(self, p=None, *args, **kwargs): super(ProductSelectForm, self).__init__(*args,**kwargs) if p: self.fields['related_obj'].queryset = Product.objects.filter( Q(product_key__iexact=p)).distinct() class Meta: model = Review fields = ['related_obj'] Note that I have also tried the above forms.py code with the Select widget instead of RadioSelect and I still get the same error. HTML: ... {% for choice in form.related_obj.field.queryset %} <label> <li> <div> <input type='radio' name='related_obj' value='{{ choice.product_key }}' required> </div> <div class='rate-obj-li-meta'> <h4>{{ choice.name }}</h4> </div> </li> </label> {% endfor %} ... models.py: class Product(models.Model): name = models.CharField(...) product_key = models.SlugField(...) class Review(models.Model): related_obj = models.ForeignKey(Product,...) review = models.TextField Tried so far: Changing RadioSelect widget to Select Changed HTML … -
Django ImportError: PIL in Apache2
I have a trouble to running Django with Apache2. It makes a error when meet a code with "import PIL" or "import Image". In error.log [Mon Apr 02 14:54:35.553626 2018] [wsgi:error] [pid 4806] [remote 127.0.0.1:13590] from PIL import Image [Mon Apr 02 14:54:35.553634 2018] [wsgi:error] [pid 4806] [remote 127.0.0.1:13590] ImportError: No module named 'PIL' But the interest thing is when i command "runserver" with Django, It works very clearly. Could you give me any solution about this problem? It is setting of apache2.conf WSGIDaemonProcess mysite python-home=/var/www/mysite/virtualenv python-path=/var/www/mysite WSGIProcessGroup mysite WSGIScriptAlias / /var/www/mysite/mysite/wsgi.py process-group=mysite Thanks. -
how to define middleware only for certain paths in django?
is there anyway to define middleware for specific route or route groups in django? like laravel which we can define it as follows: Route::get('admin/profile', function () {})->middleware('auth'); -
Django path missmatch
I have problem with my urls. Path of my site in localhost is: http://127.0.0.1:8000/detska-kniznica When I want to register i will click on the button and path looks like this: http://127.0.0.1:8000/detska-kniznica/login And when I will will submit form path looks like this: http://127.0.0.1:8000/detska-kniznica/login/logUser Problem is when I type incorrect password or username django returns forms to the same url so: http://127.0.0.1:8000/detska-kniznica/login/logUser And when I will again type correct username and password url looks like this: http://127.0.0.1:8000/detska-kniznica/login/login/logUser and this url does not exist. I will show you my urls: urlpatterns = [ path('detska-kniznica', include('homepage.urls')), path('detska-kniznica/admin', admin.site.urls), path('detska-kniznica/games', include('games.urls')), path('detska-kniznica/register', include('register.urls')), path('detska-kniznica/login', include('login.urls')), ] and urlpatterns = [ path('', views.index), path('/logUser', views.log_user), path('/logOut', views.log_out_user), ] my HTML submit button do this: <form action="login/logUser" method="post" novalidate> and my views.py looks like this: elif request.method == 'POST' and 'btn_login' in request.POST: form = inputForms.LogUser(request.POST) if form.is_valid(): print(form.errors) user_name = form.cleaned_data['username'] user_password = form.cleaned_data['password'] user = authenticate(username=user_name, password=user_password) if user is not None: print("som tu") request.session.set_expiry(86400) # sets the exp. value of the session login(request, user) # the user is now logged in else: print("help") print(form.errors) return render(request, "login.html", {'LogUser': form}) return HttpResponseRedirect('/detska-kniznica') else: print(form.errors) return render(request, "login.html", {'LogUser': form}) line above shoul return /login … -
Hello, I"m unable to get my viewpage on my polls projecr
I'm unable to open my view page in django for my project polls. The URL is launched, but it is not opening and showing an error page as attached below. The link to URL is http://127.0.0.1:8000/ Could anyone help me to rectify the error? Thank you. -
Django & ajax : Filtring data returned from Ajax
I'm new to Ajax and I'm really stuck in filtring the data I get from ajax request: $("#id_type").change(function () { var url = $("#personForm").attr("data-tiers-url"); // get the url of the ` load_cities` view var typeID = $(this).val(); $.ajax({ // initialize an AJAX request url: url, data: { 'tiers': typeID // add the country id to the GET parameters }, success: function(data) { // `data` is the return of the `load_cities` view function alert(); $("#id_facture").html(data); } }); }); this is the data variable content: <option value="3" >3</option> <option value="4" >4</option> <option value="5" >5</option> I need to give $("#id_facture") just the options that have as value="3" I tryed filter and find but didn't work. Any help Please I was stucking here for a lot of time. Thank You -
Enable IIS Anonymous Authentication for Django App
I have a Django app deployed to IIS 8.5 as two folders (code base and static files) under a site. The app includes LDAPS authentication. Therefore, I would like to enable anonymous authentication on the app's folders to avoid two logins for the user. Current structure: Server - Site - DjangoApp - DjangoAppStaticFiles - SomeOtherWindowsAuthenticatedApp - AnotherWindowsAuthenticatedApp Steps I've Taken: Enabled only Anonymous Authentication on DjangoApp and DjangoAppStaticFiles This results in this error: I then tried adding IUSR to both the folders in IIS and the Physical Path folder, to no avail. What other steps do I need to take to enable Anonymous Authentication safely? -
How do I use serializer validation in function-based view? Django Rest
I want to be able to update instances through GET requests. urls.py urlpatterns=[ url( r'^classes/(?P<pk>\d+)/add_student/(?P<student_id>\d+)', views.add_student ), ] views.py def add_student(request, pk, student_id): class_ = get_object_or_404(Class, id=pk) student = get_object_or_404(Student, id=student_id) class_.students.add(student) return redirect('class-detail', pk=pk) models.py class Class(models.Model): students = models.ManyToManyField('Student', related_name='classes') ... class Student(models.Model): ... serializer.py class ClassSerializer(serializers.ModelSerializer): def validate(self, data): ... This would successfully add a student to the class, but the validation method in my serializer would not be called. How do I update like this, and have it validated by the serializer? -
Matching URL with multiple parameters Django
Here what i am trying to accomplish is to get URL parameters value from the URL http://127.0.0.1:8000/sample/redirect_login/?request_token=9I0KoKcgdKH0s6w1Qzp6t5P2czlyxPum&action=login&status=success I have created similar URL path in my urls.py but looks like they are not matching path('redirect_login/?request_token=<str:request_token>&action=<str:action>&status=<str:status>',views.redirectLogin, name = "redirectLogin"), I want to get the parameters 1. request_token 2. action 3. Status Kindly help how to go about this? Should i be using REGEX for url matching ? Thanks -
How to make integrate Django with Kafka using Python?
I want to pass input from Django to Kafka. I have fields a,b,c,d and h1,h2 and h3. All fields are input from the user. I want to start my Kafka process as soon as the user enters submit button on my Django front-end interface. All fields are being saved in Mysql. I can only find possible solutions in Java using Mysql connectors. Is there any method or connector with which i can pass my input from user on Django interface to kafka using python ? a,b,c,d - Access Tokens h1,h2,h3 - Search queries(keywords) -
comment reply in django (review)
i wrote my own comment system in django, but i dont know if its the proper way to achieve this functionaliy. the comment style is like facebook, so you have one comment and replies associated to that comment. please review my code. models.py class Comment(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE) user = models.ForeignKey('auth.User', on_delete=models.CASCADE) message = models.CharField(max_length = 250) class CommentReply(models.Model): whichcomment = models.ForeignKey(Comment, on_delete=models.CASCADE) user = models.ForeignKey('auth.User', on_delete=models.CASCADE) message = models.CharField(max_length = 250) blog = models.ForeignKey(Blog, on_delete=models.CASCADE) views.py def PostDetail(request, pk): form1 = CommentForm form2 = CommentReplyForm data1 = Blog.objects.get(pk=pk) com = Comment.objects.filter(blog=data1) replycom = CommentReply.objects.filter(blog=data1) if request.method == 'POST': if request.POST.get('whichcomment'): data3 = CommentReplyForm(request.POST) if data3.is_valid(): whichcomment = int(request.POST.get('whichcomment')) message = data3.cleaned_data['message'] CommentReply.objects.create( whichcomment = Comment.objects.get(id=whichcomment), user = User.objects.get(username=request.user.username), message = message, blog=data1 ).save() return HttpResponseRedirect(reverse('postdetail', args=(), kwargs={'pk': pk})) #return render(request, 'postdetail.html', {'data1': data1, 'form1':form1, 'com':com, 'form2':form2, 'replycom':replycom}) else: data2 = CommentForm(request.POST) if data2.is_valid(): blog = data1, message = data2.cleaned_data['message'] Comment.objects.create( blog=data1, user= User.objects.get(username=request.user.username), message=message ).save() return HttpResponseRedirect(reverse('postdetail', args=(), kwargs={'pk': pk})) else: return render(request, 'postdetail.html', {'data1': data1, 'form1':form1, 'com': com, 'form2':form2, 'replycom':replycom}) template file <form method="POST"> {% csrf_token %} {{ form1 }} <button type="submit">submit</button> </form> {% for comments in com %} <p>{{ comments.user }} --- {{ comments.message }} {% … -
Upload File - Django and Ajax with Custom Data
I'm trying to upload an image file to Django Image object using Ajax. Yes there are other relevant questions however I was not able to solve my problem due to having to submit custom data, and not able to submit a form in its entirety (I'm working with data in custom tags and not necessarily the value of the form object). A shortened version of my Ajax code: //Add click event to btnSave $('#btnProjectInfoSave').click(function () { var project_id = document.getElementById("txtProjectId").value; var project_name = document.getElementById("txtProjectName").value; var eOwner = document.getElementById("cmbOwner"); var project_owner = eOwner.options[eOwner.selectedIndex].getAttribute("pk"); var project_logo = document.getElementById("fiLogo").files[0]; $.ajax({ url: "/raidApp/updateProjectInfo/", type: "post", data: { 'projectId': project_id, 'projectName': project_name, 'projectOwner': project_owner, 'projectLogo' : project_logo, 'csrfmiddlewaretoken': '{{ csrf_token }}' }, success: function (data) { alert("Project data saved successfully"); window.location = ('/app/myProjects/projects/' + project_id + '/projectsTab/'); } }); }); Code on Django side: def updateProjectInfo(request): if request.method == 'POST': projectId = request.POST.get('projectId', '') project = Projects.objects.get(pk=projectId) project_Name = request.POST.get('projectName', '') project_Owner = request.POST.get('projectOwner', '') project_owner_object = Resources.objects.get(pk=int(project_Owner)) project_logo = request.POST.get('projectLogo', '') project.name = project_Name project.owner = project_owner_object project.logo = ImageFile(open(project_logo, "rb")) project.save() return(HttpResponse('Success')) I get the following JS error: jquery.min.js:2 Uncaught TypeError: Illegal invocation at i (jquery.min.js:2) at jt (jquery.min.js:2) at jt (jquery.min.js:2) at …