Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Loop through model names
I want to loop through several models with my data generator function. Currently my page doesn't load and it just says This site can’t be reached. Anyone knows what I am doing wrong? # Reset database models = ['ReservedItem', 'Ticket', 'Event', 'Organizer', 'User'] for _model_name in models: **_model_name.objects.all().delete() print("Deleted ", model_name) -
JSONDecodeError Django
I have an API that is sending me a POST request (JSON) for testing. I was doing a lot with the JSON, but all of a sudden it stopped working and giving me a JSONDecodeError. I tried all sorts of things, like using request.POST but nothing worked correctly like I said this was working at one point. Any assistance is appreciated. View: def webhook_receiver(request, *args, **kwargs): if request.method == 'POST': # Get the incoming JSON Data data = request.body.decode('utf-8') received_json_data = json.loads(data) return HttpResponse(received_json_data) else: return HttpResponse("not Post") Error given pastebin -
Mezzanine contact form produces "upstream prematurely closed" error
My website uses Mezzanine 4.2.3 with Django-Oscar 1.5.2 and Django 1.10.8, running on Ubuntu 16.04 on Digitalocean. When customers purchase a product, the site successfully sends them a confirmation email. But when customers use the Mezzanine contact form that I made by following the demo page created with createdb exactly, I get a 502 bad gateway. The nginx error log records this error: *13 upstream prematurely closed connection while reading response header from upstream. The number varies between *1, *7, and *13, but the text is the same. I googled this and found various possible solutions, including these: Increasing the timeout for nginx proxy_pass. This involved adding proxy_connect_timeout 75s; and proxy_read_timeout 300s; to nginx config, and then adding --timeout 300 to gunicorn. This produced an actual timeout error: *21 upstream timed out (110: Connection timed out) while reading response header from upstream, Uncommenting precedence ::ffff:0:0/96 100 in /etc/gai.conf.. Unblocking port 587 in UFW. Making nginx listen on port 587: server {listen 80; listen 587; ... list 443 ssl; ...}. The site is running well, it sends confirmation emails when customers purchase a product, and only the contact form doesn't work. I'm out of ideas. What am I missing? -
track which app created a proxied object from the non proxied
I have a base app that has an Article class. An article can be created from other apps and I had been able to save an "app name tag" for it. The problem is that even if I can filter all the Articles from the app that created it using a custom manager, can't find the name of the app by the name tag on the base one. This is the models.py of the baseApp: class Article(models.Model): app = models.CharField(max_length=1, choices=sub_apps) title = models.CharField(max_lenght=50) and this is the models.py of another app: from baseApp.models import Article as GenericArticle class ArticleManager(models.Manager): def get_queryset(self): return super(ArticleManager, self).get_queryset().filter( app='h') class Article(GenericArticle): objects = ArticleManager() class Meta: proxy = True As you can see there, the idea is to create the choices=sub_apps array based on the ones that proxies the Article, but I don't know how to create it. The BaseApp would be packed to be used as an independant repository, that's why I can't create the array manually. Any approach is apreciated, thanks. -
django-cities: Could not find the GDAL library
I'm using Django 2.0 and using django-cities to import country and state data to the database. I only want little information like, country name, country code, currency code, currency symbol, currency name and their associated states data like state name and state code. It is quite difficult to have all data for all countries in the world. After installing django-cities, the only changes I'm made is added cities to INSTALLED_APPS added this setting item in app.settings.py. CITIES_INCLUDE_NUMERIC_ALTERNATIVE_NAMES = True When I run manage.py migrate it gives following error django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal", "GDAL", "gdal2.2.0", "gdal2.1.0", "gdal2.0.0", "gdal1.11.0", "gdal1.10.0", "gdal1.9.0"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. Since I am not using any geographical data to plot on map, etc. I do not want to install GDAL on my system. How can I use this plugin to have only country and state data without creating a mess-up in database with data that is of no use to me? -
Can I use select2 with initialvalue from django view?
I need to use select2 in the template of my django app, but it is not working ... I do not know about ajax and jquery, so I hope you guys help me. follow my code so far <script> $(".js-data-ajax").select2({ ajax: { headers: { "Content-Type": "Application/Json", "Cache-Control": "no-cache" }, type: "GET", url: '{{url}}', #the data comes from an external source. #The URL is passed by the view to the template dataType: 'json', crossDomain : true, delay: 250, data: function (params) { return { q: params.term, access_token: '{{access_token}}' }; }, processResults: function (data, params) { var newData = $.map(data.items, function (obj) { obj.id = obj.id || obj.vehicle.text; return obj; }); return { results: newData, }; }, }, placeholder: '{{author}}', }).on("change", function(e) { var lastText = $(".js-data-ajax option:last-child").text(); document.getElementById('id_book').value = lastText; }); </script> This code works, but it still does not do exactly what I need: As you can see, I get the {{author}} parameter through the view. I need the select2 search box to be initialized with the value of this parameter, and that this parameter can be complemented with information that the user types. For example: Assuming that the value passed through the {{author}} parameter is "Andrew Stuart". I need … -
Django how to trigger validation of a class property to raise an exception
I have this function iam trying to test whether if discount amount is greater than the invoice amount then a validation error should be raised. Iam stuck in actually triggering the exception for it to be raised in the test. See below class Invoice: @property def inv_amount(self): amount = Sum(quantity * price) return amount @property def discount_amount(self): amount = Sum(discount) return amount def validate_amount(self): if self.discount_amount > self.inv_amount: raise ValidationError("discount amount cannot be greater") def_test_validate_amount_greater_than_discount(): with pytest.raises(ValidationError) as e: #Trigger the exception -
Multiple Django Forms on Single Page
I'm trying to create a form to input scores for a round of golf. A standard round of golf is 18 holes, so the form should create 18 instances of 'Score' once submitted. How would I go about creating a form that contains a single dropdown for 'player' and 18 text fields for strokes on each hole? Below are the models being used: class Score(models.Model): hole = models.ForeignKey(Hole, on_delete=models.CASCADE) player = models.ForeignKey(Player, on_delete=models.CASCADE) strokes = models.IntegerField(default=0) class Player(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) class Hole(models.Model): number = models.IntegerField() -
Submit form after multiple checkboxes are selected
I have been working on some learning platform for a while. Right now, I have a big of a trouble on how can I submit my form after multiple checkboxes are selected. For example, let's say I have some courses and I want to enroll or disenroll some students. I want to be able to select 2 or more checkboxes at a time if I want to enroll a student and then submit the form, or 2 or more checkboxes if I want to disenroll him and submit the form as well. How can I achieve that ? For now, I can do it only for one checkbox at a time. {% with crs_stud=course.student.all %} {% for student in students %} {% if student in crs_stud %} <form class="enroll" action="" method="POST"> {% csrf_token %} <label for="id_{{ student.id }}"> <p class="enrolled"> {% for std in students2 %} {% if std.student_ID == student.student_ID %} <img style="width: 40px; height:40px; margin-right:10px; border-radius:100%;" src="{{ MEDIA_URL }}{{ std.photo.url }}" class="avatar" alt="Avatar"> {% else %} <img style="width: 40px; height:40px; margin-right:10px; border-radius:100%;" src="{% static "images/profile.png" %}" class="avatar" alt="Avatar"> {% endif %} {% endfor %} {{ student.name }} {{ student.surname }} is already enrolled to {{ course.name }}.</p></label> <input … -
Django app with form with separate SUBMIT and UPLOAD buttons
My index.html file contains one large form which gets tons of user input. Towards the end of the form, I want to give the user an option to upload a file using a button. But this should not trigger the form submission because they may want to continue entering data into other parts of the form. Here is a basic overview of the HTML: ((some other stuff)) <form id="outer_form"> ((other HTML stuff)) <form enctype="multipart/form-data" method="post" action="{% url 'my_app:upload_file' %}" id="file-upload-form"> {% csrf_token %} <input type="file" name="file" style="display: none"> <button type="button" class="btn btn-primary" id="btn-upload-file">Upload file</button> </form> ((more other stuff)) ((submit button for the outer form)) </form> ((other stuff)) Of course, this won't work because I have nested FORM elements which is illegal. How can I combine these two ideas, keeping the CSFR token and using the correct django action for the upload button? Thanks! -
Django Celery Periodic Task at specific time
I am using celery==4.1.1 in my project. In my settings.py, I have the following: from celery.schedules import crontab CELERY_BROKER_URL = "redis://127.0.0.1:6379/1" CELERY_TIMEZONE = 'Asia/Kolkata' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_RESULT_BACKEND = "redis://127.0.0.1:6379/1" CELERY_BEAT_SCHEDULE = { 'task-number-one': { 'task': 'mathematica.core.tasks.another_test', 'schedule': crontab(minute=45, hour=00) }, 'task-number-two': { 'task': 'mathematica.core.tasks.test', 'schedule': crontab(hour='*/1') } } The second task mentioned in CELERY_BEAT_SCHEDULE is running perfectly. However, the first task mathematica.core.tasks.another_test which is a simple function returning a string is not running at the specified time, 00:45 (45 minutes past midnight). I have tried a number of ways to run a function at a given time each day but failed to achieve the same. Please suggest ways/hints to achieve the same results. -
How can I enter email data during signup in Django views
When people sign up in my website, I let them only to put username and password, and I let them put their email in the username section. However, I need the Django default email section to be inputted when they put their email in the username section. Currently, my form only has username and password section, so when they submit the form, I wanna put the data in the username section in email section. form.email doesn't work. How can I do that? def signup(request): if request.method == 'POST': form = SignupForm(request.POST) if form.is_valid(): form.email = request.POST['username'] # I need something like this user = form.save() return redirect(settings.LOGIN_URL) # default : "/accounts/login/" else: form = SignupForm() return render(request, 'accounts/register.html', {'form': form}) -
Django UpdateView .get_initial returns empty
I have two UpdateViews, one works and the other doesn't... The working model is: views.py class JuryUpdate(UpdateView): model = Jury fields = [ 'jury_name', ] template_name_suffix = '_update_form' def get_object(self, *args, **kwargs): return get_object_or_404(Jury, jury_id=self.kwargs['jr']) def form_valid(self, form): form.instance.customer_id = self.kwargs['pk'] form.instance.court_year = self.kwargs['yr'] form.instance.jury_id = self.kwargs['jr'] return super(JuryUpdate, self).form_valid(form) templates/jury_update_form.html (in relevant part) <div class="container"> <h5>Update {{for.instance.jury_name}}</h5> <form method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Save" /> </form> </div> This setup will render an updateview with the object labels and existing field data from the object. This next setup doesn't work... views.py class CustomerUpdate(UpdateView): model = Customer fields = [ 'Customer', ] template_name_suffix = '_update_form' def get_object(self, *args, **kwargs): return get_object_or_404(Customer, customer_id=self.kwargs['pk']) def form_valid(self, form): form.instance.customer_id = self.kwargs['pk'] return super(CustomerUpdate, self).form_valid(form) templates/customer_update_form.html (in relevant part) <div class="container"> <h5>Update {{form.instance.customer}}</h5> <form method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Save" /> </form> </div> The second updateview does provide an update form but it doesn't populate with the calling object's data. It would seem that the object is there since the {{form.instance.customer}} contains the correct customer data for the call (no different than the JuryUpdate view). I've tried to explicitly call get_initial (as described here) and print, but the result … -
NoReverseMatch at /basic_app/user_login/
Register works but login doesn't for some reason even though I've rechecked the template tagging properly. I'm using a custom login model, not using the admin authentication model. this is the at basic_app/urls.py from django.conf.urls import url from basic_app import views app_name = 'basic_app' urlpatterns = [ url('register/',views.register,name='register'), url('user_login/',views.user_loginPls,name='user_login'), ] and code at base.html <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> <nav> <div class="container"> <ul> <li><a href="{% url 'index' %}">Home</a></li> <li><a href="{% url 'admin:index' %}">Admin</a></li> <li><a href="{% url 'basic_app:register' %}">Register</a></li> {% if user.is_authenticated %} <li><a href="{% url 'logout' %}">Logout</a></li> {% else %} <li><a href="{% url 'basic_app:user_login' %}">Login</a></li> {% endif %} </ul> </div> </nav> <div class="container"> {% block body_block %} {% endblock %} </div> </body> </html> and code at view.py from django.shortcuts import render from basic_app.forms import UserForm,UserProfileInfoModelForm #imports from django.contrib.auth import authenticate, login,logout from django.http import HttpResponseRedirect, HttpResponse #changed from django.core.usrlresolvers to django.urls #cant use reverse as it has been deprecated from django.urls import reverse from django.contrib.auth.decorators import login_required # Create your views here. def index(request): return render(request,'basic_app/index.html') @login_required def special(request): return HttpResponse('your logged in nice!!!') @login_required def user_logout(request): logout(request) return HttpResponseRedirect(reverse('index')) def register(request): registered = False if request.method == 'POST': user_form = UserForm(data=request.POST) profile_form = … -
Celery result shows disabled
I'm new to celery. After I install celery in my django app, I run the following command in the Django shell: import os from celery import Celery from django.apps import apps app = Celery('') app.config_from_object('ns.settings') @app.task def add(x, y): return x + y I can get the result: In [5]: add.delay(4,4) Out[5]: <AsyncResult: f632d828-07d5-4f6b-b538-2aee6617b7ab> I think the async task is built successfully but I can't get any result like this: In [4]: result = add.delay(4,4) Start from server, version: 0.9, properties: {'information': 'Licensed under the MPL. See http://www.rabbitmq.com/', 'product': 'RabbitMQ', 'copyright': 'Copyright (C) 2007-2018 Pivotal Software, Inc.', 'capabilities': {'exchange_exchange_bindings': True, 'connection.blocked': True, 'authentication_failure_close': True, 'direct_reply_to': True, 'basic.nack': True, 'per_consumer_qos': True, 'consumer_priorities': True, 'consumer_cancel_notify': True, 'publisher_confirms': True}, 'cluster_name': 'rabbit@rabbit', 'platform': 'Erlang/OTP 19.2.1', 'version': '3.6.15'}, mechanisms: ['AMQPLAIN', 'PLAIN'], locales: [u'en_US'] [13:49:41] amqp _on_start():340 Start from server, version: 0.9, properties: {'information': 'Licensed under the MPL. See http://www.rabbitmq.com/', 'product': 'RabbitMQ', 'copyright': 'Copyright (C) 2007-2018 Pivotal Software, Inc.', 'capabilities': {'exchange_exchange_bindings': True, 'connection.blocked': True, 'authentication_failure_close': True, 'direct_reply_to': True, 'basic.nack': True, 'per_consumer_qos': True, 'consumer_priorities': True, 'consumer_cancel_notify': True, 'publisher_confirms': True}, 'cluster_name': 'rabbit@rabbit', 'platform': 'Erlang/OTP 19.2.1', 'version': '3.6.15'}, mechanisms: ['AMQPLAIN', 'PLAIN'], locales: [u'en_US'] using channel_id: 1 [13:49:41] amqp __init__():108 using channel_id: 1 Channel open [13:49:41] amqp _on_open_ok():445 Channel open … -
Django Query from post using a serializer
Here is what I am trying to do. POST to API Create serializer so only certain fields will be passed into the query Create view that will only use the serialized fields Create query object that uses the data passed through the serializer POST works and gets the request to the view { "city": "Denver" "state": "CO" "Foo": "foo2" } Serializer WRONG When someone posts I dont want just any old variables to be sent to the query later on so I would need to clean the request through a serializer that only has "city" and "state" and does allow for "foo" to be passed into the query. NOTE EventsSerializer is for the entire model and well only be used on the view return. class EventsSerializer(??????????): class Meta: model = Events fields = '__all__' class EventQuerySerializer(serializers.BaseSerializer): class Meta: fields = ('city', 'state') View should take city and state (or other accepted fields) and query Events class QueryEvents(APIView): @staticmethod def post(request): serializer = EventQuerySerializer(data=request.data) if serializer.is_valid(): events = Events.objects.get(?????????) return Response(EventsSerializer(events).data) -
Get User information and pass them into payload
How can I retrieve single user information, and pass them into payload so I can do a post request to the external api. I need to do this for every user in the database. Potentially I'll do something like: try: user = Profile.objects.get(pk=user_id) except Profile.DoesNotExists: return None and then after that I need to pass them into payload so I can use requests lib and do a post request. r = requests.post('http://httpbin.org/post', data = {'id':'user_id', 'username': 'username', 'email': 'email', 'credit': '100'...}) How can I construct this? -
jquery /ajax post list is being posted with [ ] in the end
I'm posting an jquery/ajax with django end sending a dict but im my view I'm getting the areas like this {'areas[]': ['4', '5'],...} Myform its ok but the areas to get the key I have to use 'areas[]' How can I get just like this 'areas' without the brackets ? thanks var detail = { myForm: form.serialize(), 'areas':list_area } $('#project_form_id').on('submit', function(event){ event.preventDefault() var form = $(this) var detail = { myForm: form.serialize(), 'areas':list_area } $.ajax({ url: "{% url 'project_create' %}", method: "POST", data:detail, dataType: 'json', headers: {'X-CSRFToken': '{{ csrf_token }}'}, success: function(response){ console.log('success') console.log(list_area) $('#project_form_id').reset(); }, error:function(error){ console.log(error) //$("#modal-book .modal-content").html(data.html_form); } }); }) -
DRF API endpoint getting "Authentication credentials were not provided"
I am building some API endpoints with DRF. Here is code snippet. class ReportsDashboardView(views.APIView): permission_classes = ( IsAuthenticated, IsActiveUser, ) def get(self, request, format=None): ... I tried to call API via postman basic authentication. But it always returns "Authentication credentials were not provided." Here is code snippet for Authentication configuration. REST_FRAMEWORK['DEFAULT_AUTHENTICATION_CLASSES'] = ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.BasicAuthentication', ) I am not sure why basic authentication (username, password) is not working for me. Is this something you faced before? Would you like to help me? -
Python/Pandas to_csv saving as NoneType and raising TypeError
I am attempting to create an upload tool that takes an .xls file and then converts it to a pandas dataframe before finally saving it as a csv file to be processed and analyzed. After the file comes out of this code: def xls_to_csv(data): #Formats into pandas dataframe. Index removes first column of .xls file. formatted_file = pd.read_excel(data, index_col=0) #Converts the formatted file into a csv file and saves it. final_file = formatted_file.to_csv('out.csv') It saves properly and in the right location, however when I attempt to plug the resulted file into other functions that contain loops, I raise a TypeError: 'NoneType' object is not iterable. The file is saved as 'out.csv' and I am able to open it manually, however the open command won't even work without this error being raised. Using Python 3.6! Thanks in advanced! -
why DAMP(Django Angular MongoDB Python) Stack is not popular?
recently i came around MEAN Stack, LAMP Stack , MERN Stack, but, i never heard of DAMP(As shown in title) Stack. Is it available, if so how good is it? If not, can you help me with why this might or might not be a good idea! -
Django - User Defined Queryset Filtering
I am working on an application where end users need to be able to define queryset filters through an interface. These filters are used to select instances of a model to ship off to another web service at timed intervals. Contrived example: class Thing(models.Model): stuff = models.CharField() I need users to be able to configure a timed task where only Things with a value of test for the stuff field will be selected. I currently have a working POC for this functionality, but it involves a lot of hand coded logic. Given that django has such a rich community and ecosystem, I was wondering if I am missing an opportunity to do this in a simpler way. Looking forward to your feedback! -
What is the best django tutorials for beginners [on hold]
Want to know the source of django 2.0 for beginners -
Logging internal server errors by Nginx and Django
I'm trying to log internal server errors that occur through my django app. I've set up locations for both access logs and error logs through nginx configuration (nginx.conf): http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ... I've simply reloaded nginx after setting this. Every access is logged in access.log file without any problems but internal server errors are never logged in error.log file, but nginx does have access to it since the only thing that it contains is [notice] 23802#0: signal process started). I have a certain API in my django application that returns json (for Ajax). Unfortunately some internal error has occurred on that certain view (Ajax only logged status code and error name). I think internal server errors are not to be handled by Nginx, Is this true? If so, do I need to manually log internal server errors through Django? (process_exception()?). If not, is there something wrong with nginx configuration. Thank you! -
repetitive sending data to django template from view
I am using twitter streaming api for fetching real time tweets and I want to display the data of tweets as they come. I can't use HttpResponse() or render() to send data from view to template because it sends data only once. I want to send data repetitively as they come. now how can I achieve that? I have few ideas like I can use javascript to refresh page after few seconds but that doesn't seem good idea. I know it is not good to provide no code but I have not implemented anything regarding that.