Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
manage.py runserver fails after putting custom app in middleware
Im following a guide on youtube to work with django. Unfortunately this guide is made for pre 2.0 django. So the challenge is to create a app called "posts" that can be accessed by localhost/posts. After creating the folder 'posts' and adding it to settings.py MIDDLEWARE like this: MIDDLEWARE = [ 'posts', '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', ] python manage.py runserver fails When commenting 'posts' out runserver succedes. The problem is that Im so new to all of this that I don't even know what to search for. -
Django send too many message with Messenger Bot
I tried sending a message to my Facebook account from My Facebook page, but it sends too many messages and never stop till restarting server and change views.py code. from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt import requests import json @csrf_exempt def hello(request): response_msg = json.dumps({"recipient":{"id":"1786715484701833"}, "message":{"text":"hi!"}}) requests.post("https://graph.facebook.com/v2.9/me/messages?access_token=<page-access-toke>",headers={"Content-Type": "application/json"},data=response_msg) return HttpResponse("pong") When i removed headers it doesnt send any message, what is the problem about this? -
Django: Different level of logging on server and locally
I've set the logging level to INFO for loggers and handlers. Everything works as expected when I run Django on my local machine with ./manage.py runserver. However, on Apache server with WSGI, the log contains only WARNING logs. The DEBUG variable is set to True in both cases. Here is critical part of my settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'normal': { 'format': '%(levelname)s %(asctime)s %(module)s %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': '/var/log/clawd.log', 'formatter': 'normal' }, 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'normal' }, }, 'loggers': { 'django': { 'handlers': ['file', 'console'], 'level': 'INFO', 'propagate': True } } } State of the log after GET request on the local machine: INFO 2018-01-18 22:07:38,935 basehttp "GET /case/new/doc/1 HTTP/1.1" 200 337 On the server: Any idea how could that happen? How Django even knows that it is running on a server when the DEBUG flag is still True? -
why post method looks as 'OPTIONS' in django
I simply post a file to django app which hosted in virtual machine. and request logs looks like; [18/Jan/2018 21:49:06] "OPTIONS /upload/ HTTP/1.1" 200 0 I searched and installed django-cors-headers nothing looks wrong but whats this options stuff? why django doing this? here is function in django: def upload_file(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES['file']) return HttpResponseRedirect('/success/url/') else: form = UploadFileForm() return render(request, 'upload.html', {'form': form}) -
Filter form field based on another form field (user selects date, then another field displays timeslots available that day)
I'm trying to filter the slot (time slot) field based off of the day field the user selects. So basically filter the slot field to only show the ones that exist on that day. I have successfully been able to filter it based off if the time slot is booked, but can not get it to dynamically filter based off the date field. I have two models. Appointment, and Calender (I refer to the rows in this table as time slots) Models class Calendar(models.model): date = models.DateField() timeslot_A = models.TimeField() timeslot_B = models.TimeField() booked = models.BooleanField(default=False) class Appointment(models.Model): """Appointment Information""" client = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) date_added = models.DateTimeField(auto_now_add=True) day = models.DateField(u'Day of the event', help_text=u'Day of the event') slot = models.OneToOneField(Calendar, on_delete=models.CASCADE) Forms.py class AppointmentForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(AppointmentForm, self).__init__(*args, **kwargs) self.fields['slot'].queryset = Calendar.objects.filter(booked=False, date=self.instance.day) #HERE^^^^^^^^^^^^^^^^ class Meta: model = Appointment fields = ['day', 'slot', 'notes', 'recurring', 'extras'] widgets = { 'day': forms.DateInput(attrs={'id': 'datepicker', 'type': 'select'}), } I know how to achieve this using jquery, but I'm pretty sure that't not ideal since it's filtered on the front end. -
Pass Django Variable Via Javascript
I'm new to Javascript, and trying to figure out how to get the value of a variable in my HTML form. I have the following code kind of working, I put an alert in to test my logic and the else statement is working, but I can't seem to figure out how to get Javascript to submit my form if the value is set to on. I know my value is being interpretted correctly as I tested it with an alert as well. It just doesn't seem to want to submit the form. I have looked through SO and it seems that the Javascript submit syntax might have changed? Here is my Javascript function: document.getElementById('ifon').onclick = function(){ var getval = Checkbox(this.form); if (getval == 'on') { document.getElementById("data").submit(); } else { alert(getval); } } And here is my HTML for the form in question: <form id="data" name="data" %}"> <input type='hidden' name='status' value="Delete"> </form> I'm new to Javascript so maybe I'm missing something. This is a checkbox and Javascript seems to know what the value is based on my testing. I just can't seem to get the form to submit. Thanks for the help in advance. -
Passing a Django object into javascript?
I have the following "object" within my views that I'm passing into my template via the context: def objects(request) events = Object.objects.filter(Q(when__gt=datetime.datetime.now().date())).order_by('-when') context = { 'events': events, } return render(request, "thinkingplace/events.html", context) I'm then attempting to use this for jQuery uses on the front end template: <script type="text/javascript"> var events = '{{ events }}'; console.log(events); </script> I've tried using template tags - but I receive the "object is not JSON serializable error" - I've tried all manner of things but nothing is work. Does anyone have any ideas?? -
Django rest framework serialize ArrayField as string
I have a field in my Model class with an 'ArrayField' and I want it to serialize back and forth as a string of values separated by comma. models.py from django.contrib.postgres.fields import ArrayField class Test(models.Model): colors = ArrayField(models.CharField(max_length=20), null=True, blank=True I followed this solution - https://stackoverflow.com/questions/47170009/drf-serialize-arrayfield-as-string#= But getting bellow error - TypeError: to_representation() takes 2 positional arguments but 3 were given Please help. -
Any IDE provide an environment for AngularJS4(front-end) and DJango(back-end) development
I have searched a lot but could not find any satisfying answer. I want to know if any IDE provide environment for web development using Angular and DJango. please tell me. I will be thankful for your guidence. -
Is it possible to have a Heroku app I built be on the same domain as my Wordpress website?
I have a website hosted on Wordpress at domain [my domain name].com. I built an app using Django that is currently deployed on Heroku at [my domain name].herokuapp.com. The apps do not have conflicting routes. For example, the '/' route does not exist on the app I built myself. Is it possible to configure my DNS settings on Heroku such that I can use my custom domain name where a Wordpress website already lives? -
how to filter Django objects with a varying number of filter terms
Users can search for articles in my database with a set of terms. For example, "police body camera force". I then want to return to the user a list of articles where the title or source of the article contains ANY one of the terms the user entered. I'm not sure how to do this, especially since I don't know how many words there will be in the user's query. I thought the code would be something like this: user_query = "police body camera force" user_query_term_list = user_query.split(' ') for term in user_query_term_list: results = Article.objects.filter(Q(title__icontains="term")|Q(source__icontains="term")) ...and then somehow combine each of the results together in one queryset. If this is the most efficient approach, how do I combine the results from each of the loops into one queryset? And if there is a better way of accomplishing my goal, I would be grateful for the advice. Thank you. -
How can I force django to restart a database connection from the shell?
I have a django project on a Digital Ocean server. From my local machine, I connect to the database through ssh: ssh -L 63333:localhost:5432 me@my.server And change my local settings.py as: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': '', 'USER': '', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': 63333 } } And on a Jupyter QtConsole on my local machine, I follow these steps for setup: import os import django os.chdir('/path/to/my/project') os.environ['DJANGO_SETTINGS_MODULE'] = 'my_project.settings' django.setup() It all works fine until my ssh connection is broken by some reason. First I get this error (on a line that queries the database, say, my_model.objects.first()): DatabaseErrorTraceback (most recent call last) /home/ayhan/anaconda3/lib/python3.6/site-packages/django/db/backends/utils.py in _execute(self, sql, params, *ignored_wrapper_args) 84 else: ---> 85 return self.cursor.execute(sql, params) 86 DatabaseError: server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request. When I reconnect through ssh, I keep getting the following error: InterfaceErrorTraceback (most recent call last) /home/ayhan/anaconda3/lib/python3.6/site-packages/django/db/backends/base/base.py in _cursor(self, name) 233 with self.wrap_database_errors: --> 234 return self._prepare_cursor(self.create_cursor(name)) 235 /home/ayhan/anaconda3/lib/python3.6/site-packages/django/db/backends/postgresql/base.py in create_cursor(self, name) 211 else: --> 212 cursor = self.connection.cursor() 213 cursor.tzinfo_factory = utc_tzinfo_factory if settings.USE_TZ else None InterfaceError: connection already closed The error only goes away if I restart the IPython … -
Django Query set is empty on chosen.js multiselect... Why?
I'm going to simplify my problem by focusing on one example I have the following javascript that determines which chosen multiselect option will be shown based on another select option. Everything is working correctly with the JS. For my problem i'm only going to show the group option selected. $(document).ready(function () { $('#accesslevelid').change(function () { $this = $(this) $('.content_box').each(function () { $select = $('select', this); if ($select.data('id') == $this.val()) { $(this).show(); $select.show().chosen(); } else { $(this).hide(); $('select', this).hide(); } }); }); }); Inside my form I have the following: {% block extra_js %} {{ block.super }} {{ form.media }} <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.js" type="text/javascript"></script> <script src= "{% static '/accounts/chosen.jquery.js' %}" type="text/javascript"></script> <link rel="stylesheet" href="{% static '/accounts/chosen.css' %}"> <div id = "div_groupdimselect" class="content_box"> <select data-placeholder="Choose a group..." data-id="4" class="chosen-select" multiple tabindex="4" id = "id_groupdimselect" value = "{{facility.blevel}}" style="width: 1110px"> {% for facility in facilitydim %} <option value="{{facility.group_name}}">{{facility.group_name}}</option> {% endfor %} </select> </div> With my view I'm attempting to access the users chosen selection with the following, the datareducecode works when i filter on the users coid, but when i try datareducecode1 it returns and empty set: grouplist = request.POST.getlist('blevel') if request.method == 'POST' and selectedaccesslevel == '4': datareducecode = OrgLevel.objects.filter(coid__exact = owner.coid).values_list('blevel', flat … -
post request method equals ''options" in Django
I have posted a file from host machine to virtual machine which drjango restfull service running, I need to upload the file via this method def upload_file(request): if request.method == 'POST': # request.method = 'OPTIONS' form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES['file']) return HttpResponseRedirect('/success/url/') else: form = UploadFileForm() return render(request, 'upload.html', {'form': form}) but request method equals to 'OPTIONS', I Searched on net and understood its about cros but I need exact guide to handle this issue. -
Django data leak between 2 separated tests
In my whole tests base, I experience a weird behaviour with two tests. They are completely isolated. However, I can find data from the first test in the second one. Here are the tests: file1 (services.tests) class ServiceTestCase(TestCase): @patch('categories.models.ArticlesByCategory.objects.has_dish_type') def test_build_dishtype_conflicts(self, mock_has_dish_type): # WARN: create interference in tests restaurant = RestaurantFactory() dt_1 = DishTypeFactory(restaurant=restaurant) cat_1 = CategoryFactory(restaurant=restaurant) art_1 = ArticleFactory(name='fooA1', restaurant=restaurant) art_2 = ArticleFactory(name='fooA2', restaurant=restaurant) abc_1 = ArticlesByCategory.objects.create(category=cat_1, article=art_1, is_permanent=True, dish_type=dt_1) abc_2 = ArticlesByCategory.objects.create(category=cat_1, article=art_2, is_permanent=True, dish_type=dt_1) mock_has_dish_type.return_value = [abc_1, abc_2] abcs_to_check = ArticlesByCategory.objects.filter(pk__in=[abc_1.pk, abc_2.pk]) conflicts = ServiceFactory()._build_dishtype_conflicts(abcs_to_check) self.assertDictEqual(conflicts, {dt_1.pk: 2}) file2 (products.tests) class ArticleQuerySetTestCase(TestCase): def test_queryset_usable_for_category(self): restaurant = RestaurantFactory() category_1 = CategoryFactory(name='fooB1', restaurant=restaurant) category_2 = CategoryFactory(name='fooB2', restaurant=restaurant) article_1 = ArticleFactory(restaurant=restaurant) article_2 = ArticleFactory(restaurant=restaurant) ArticlesByCategory.objects.create(article=article_1, category=category_1, is_permanent=True) queryset_1 = Article.objects.usable_for_category(category_1) # This line is used for debug for art in Article.objects.all(): print(art.name) When running test_build_dishtype_conflicts THEN test_queryset_usable_for_category in the same command, here are the results of the print in the second test: fooA1 fooA2 fooB1 fooB2 I suspect I did something wrong but can't find what. -
Django widget tweaks' render_field not working
I have this form rendering template in django, and render_field is not working inside if-else: {% load widget_tweaks %} {% for field in form %} <div class="form-group"> {{ field.label_tag }} {% if form.is_bound %} {% if field.errors %} {% render_field field class="form-control is-invalid" %} {% for error in field.errors %} <div class="invalid-feedback"> {{error}} </div> {% endfor %} {% else %} {% render_field field class="form-control is-valid" %} {% endif %} {% else %} {% render_field field class="form-control" %} {% endif %} {% if field.help_text %} <small class="form-text text-muted"> {{ field.help_text }} </small> {% endif %} </div> {% endfor %} And it renders this: But when I try a smaller version of the above code like following, then also it still doesn't work: {% load widget_tweaks %} {% for field in form %} <div class="form-group"> {% if field.errors %} {% render_field field class="form-control is-invalid" %} {% else %} {% render_field field class="form-control is-valid" %} {% endif %} {% if field.help_text %} <small class="form-text text-muted"> {{ field.help_text }} </small> {% endif %} </div> {% endfor %} And renders this: But when I remove all if-else's: {% load widget_tweaks %} {% for field in form %} <div class="form-group"> {{ field.label_tag }} {% render_field field … -
Build system for aws
I was using a free tier aws account in which I had one ec2 machine (Linux). I have a simple website with backend server running on django at 8000 port and front end server written in angular and running on http (80) port. I used nginx for https and redirection of calls to backend and frontend server. Now for backend build system, I did these 3 main steps (which I automated by running jenkins on the same machine). 1) git pull (Pull the latest code from repo). 2) Do migrations (Updating my db with any new table). 3) Restarting the django server. (I was using gunicorn). Now, I split my front end and backend server into 2 different machines using auto scaling groups and I am now using ELB (Aws Elastic Load balancer) to route the requests. I am done with the setup. But now I am having problem in continuous deployment. The main thing is that ELB uses auto scaling groups which in turn uses AMI. Now, since AMI's are created once, my first question is how to automate this process and deploy my latest code in already running aws servers. Second, if I want to run few steps … -
how to apply multiple query on multiple queryset in django
I wrote a query which is fetching some details toll_obj = Toll.objects.filter(driver__profile__invoice_number=(invoice_number)) Here toll_obj can be multiple queryset, one field is common for all objects in qs(toll_obj) that is form_date. So I want to apply one more condition here which is form_date<=today . So what can be the best way to achieve this. Any help would be appreciated. -
Django app not working on mobile only (desktop is fine)?
I'm running a Django app on a private intranet which requires either the company wifi to access or, alternatively, a VPN connection in order to open it from a non-company wifi channel. That's working as intended. The issue is that I can access the site from mobile (iPhone, iPad) when I'm on the company wifi. But when I'm connected through public wifi, even if I'm connected via VPN and I can access the intranet, I cannot access the site. For a variety of security reasons I can't disclose precise details or code, so I'm not looking for an explicit solution. Instead, I would be very, very grateful for some general ideas as to what might possibly be causing this, or things that I could start looking into and/or check. I know this isn't your typical stack overflow post, but it is definitely useful for me and I believe helpful to anybody else who runs into a similar issue if we can create a list of possible reasons for this error. -
Using Sass with Django
Im looking for a reasonably simple toolset and workflow for incorporating Sass into my Django projects. Im predominantly backend focused and have just started investigating Sass, so bear with me. My initial idea was to keep things simple by just using node-sass without trying to incorporate Gulp, django-pipeline or anything else initially. My Django apps are usually structured such that I create a static/app/css folder in each app. One option I guess would be to now create an additional folder per app for scss files, ie: static/app/scss. Next, outside of my Django project folders I would create a folder to install node-sass since I wouldn't want to install it globally and I don't want the node-modules folder inside my Django project or inside source control. I guess the node-modules folder can be thought of like using a python virtualenv instead of installing packages globally? Next, inside my Django project somewhere (not sure where?) I would have the package.json file containing a scripts section for every scss file I want compiled to css, eg: "scripts": { "compile:sass": "node-sass app1/static/app1/scss/style.scss app1/static/app1/css/style.css", "compile:sass": "node-sass app2/static/app2/scss/style.scss app2/static/app2/css/style.css", "compile:sass": "node-sass app3/static/app3/scss/style.scss app3/static/app3/css/style.css" } Lastly, I would just run compile:sass with the watch flag to constantly … -
Celery should return a non-zero exit code an exception occurs
I'm experiencing a weird situation with Celery 4.1, Python 2.7.13. When there is an issue with the connection between Python app and Database (MySQL in this case), Celery does not return a non-zero code and keep the worker running which doesn't make any sense. Although I can see the exception in the result of celery -A myapp worker -l INFO -E but the worker doesn't stop. I tried almost all options of celery worker but no luck. Is there any way to force the worker to stop working and exit if the database connection is failing? -
Trigger bootstrap modal after django form submission
How can I trigger the bootstrap modal to popup after my django form was submitted? In my index.html template I have a standard looking modal like this <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> ... </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> below in the same index.html I have a django form {{ form.non_field_errors }} {% csrf_token %} <ul id="robul"> <div class="form-group"> <div class="col-xs-6"> <li id="name" name="{{ form.name.name }}" class="form-control">{{ form.name }}</li> </div> </div> <div class="form-group"> <div class="col-xs-6"> <li id="email" class="form-control">{{ form.email }}</li> </div> </div> <div class="form-group"> <div class="col-xs-6"> <li id="contactmessage" class="form-control">{{ form.contactmessage }}</li> </div> </div> </ul> in my view.py it looks like this: if request.method == 'POST': form = forms.FormName(request.POST) if form.is_valid(): contact_name = request.POST.get( 'name', '') contact_email = request.POST.get( 'email', '') form_content = request.POST.get('contactmessage', '') template = get_template('contact_template.txt') context = {'name': contact_name, 'email': contact_email, 'contactmessage': form_content,} content = template.render(context) mail = EmailMessage("New contact form submission", content, "Some Name" +'', ['somegmail@gmail.com'], headers = {'Reply-To': "noreply@gmail.com" }) mail.send() return render(request, 'index.html', {'form': form}) -
Django (v2.0.1) form Creation and pulling data's from DB
I am learner and started using django framework for a small project. I am struggling to create a form and pulling values from the DB. I have a table "travel" in my DB which has the following fields in it. ID, customer_name, travel_date, billing_status, created_at, updated_at 1, Robin Hood, 2018-01-10, Paid, 2018-01-10 15:29:25, 2018-01-10 15:29:25 Now I wanted to have a form with the above fields which should pull all the records from the database "travelmanager" and table "travel". If someone could, provide me an example with the above details. That could be very very helpful. Thank you in advance. -
Combine two querysets from different models into one queryset
I need to combine two querysets into one queryset (the result can't be a list or other type of object) as when I iterate on the querysets in a template I need to access their relations, which cannot be done from a list or dictionary. I've tried solutions like union however this is unacceptable as I need access to the relations in the template. The loop that I need the data structure for looks like the loop below. The two relations on this object are user and aircraft. {% for key in active %} <tr> <td>{{key.user.name}}</td> <td>{{key.aircraft.tail_number}}</td> <td>{{key.departure_date}}</td> <td>{{key.departure_city|title}}</td> <td>{{key.arrival_city|title}}</td> </tr> {% endfor %} One idea is to somehow do a join between the two tables in a way that a queryset is returned however at this point I've been unable to figure out how to do that. I haven't tried raw SQL yet so maybe that's the route? -
Add a field to a model in the view
I would like to add the field unread to a chat model in the view. The field unread needs to be computed first and depends on another model called chatmessages. Right now unread can only be requested separately from a chat via detail_route: class ChatViewset(ModelViewSet): ... @detail_route(methods=['get'], ) def unread(self, request, pk): chat = self.get_object() assert isinstance(chat, Chat) all_messages = ChatMessage.objects.filter( Q(in_chat__first_participant=request.user, in_chat__blocked_by_first_participant=False) | Q(in_chat__second_participant=request.user, in_chat__blocked_by_second_participant=False), in_chat=chat) all_unread_messages = all_messages.filter( Q(in_chat__first_participant=request.user, sent_by_first_participant=False, read_by_receiver=False) | Q(~Q(in_chat__first_participant=request.user), sent_by_first_participant=True, read_by_receiver=False)) return Response({'unread': all_unread_messages.count()}) def list(self, request, *args, **kwargs): self.serializer_class = ChatSerializer return super(ChatViewset, self).list(request, *args, **kwargs) def retrieve(self, request, *args, **kwargs): self.serializer_class = ChatSerializer return super(ChatViewset, self).retrieve(request, *args, **kwargs) ... How could I integrate unread into the view of chat?