Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Gunicorn Access Logs Shows Empty User
With the below command: gunicorn --workers=4 my_project.wsgi -b 0.0.0.0:8000 --log-level=info --access-logfile=my_project/logs/gunicorn_logs.txt I am able to log every request. However, these logs do not include information about the user: 127.0.0.1 - - [02/Aug/2018:13:46:44 -0500] GET /metrics/data HTTP/1.1 200 1589185 http://localhost:8000/ Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 The default formatting string is %(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s", which, if I understand the documentation correctly, the "user name" should show up after the "referrer address" and before the "date of the request". I have also included that format string as part of the run command just to verify that the same thing happens, and it does. Is it possible for me to have Gunicorn also log the user that made the request? Any help would be appreciated. This is running Gunicorn 19.7.1 and Django 1.11.9. -
How to add serial number in django list?
I'm populating table using using for loop in django list view. While populating I want to display serial number as well in the list. {% for Attendee in filter.qs %} {% if Attendee.checkin %} <tr> <td> Serial no. </td> <td>{{ Attendee.roll_no }}</td> <td>{{ Attendee.name }}</td> <td>{{ Attendee.branch }}</td> </tr> {% endif %} As I'm using filter to display the results, it is not possible to maintain serial number in models. I want something like this: What are the other possible ways I can use to put serial numbers in list? -
Django GenericRelation recursive import
I'm trying to create a system, for a User to worte a comment on an other User. So I create a models with GenericRelation like this: App1\models.py: from django.contrib.auth.models import AbstractUser from django.contrib.contenttypes.fields import GenericRelation from app2.models import Social class User(AbstractUser): """ Default User model used for authentification system """ relation = GenericRelation(Social) # recently added App2\models.py: from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from app1.models import User class Social(models.Model): content_object = GenericForeignKey('content_type', 'object_id') object_id = models.PositiveIntegerField() content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) author= models.ForeignKey(User, # Member who wrote the message on_delete=models.CASCADE, related_name='wrote') message= models.TextField() Before adding the field relation in User. I don't have any problem but I was remake the work of GenericRelation and I want to simplify my cod. Then the problem appear when i run the server. I'm in a recursive import loop... file .\app2\models.py from app2.models import Social file .\app1\models.py from app1.models import User Would there be a possibility of solving this problem by keeping a GenericRelation on Social and GenericRelation for my User? Because after I want to add an other GenericRelation(Social) on an other model/ -
DJANGO - Using simple history, how can I show both a base model record and a related history group calculation in one query?
I am using the simple history library for my Django project. It's pretty nifty, but I'm having trouble showing aggregated history stats next to a base model object. Here's what my model looks like: from django.db import models from django.contrib.auth.models import User from simple_history.models import HistoricalRecords class RepairForm(models.Model): user_id = models.ForeignKey(User, on_delete=models.DO_NOTHING,) return_number = models.CharField(max_length=200, unique=True) status_id = models.ForeignKey(RFormStatus, on_delete=models.DO_NOTHING) ... history = HistoricalRecords() def __str__(self): return self.return_number The Docs lead me to believe the proper way of accessing historical records is using the history manager. I can get both sets of information I want: All Forms (base model objects) - RepairForm.objects.all() User ID | Return Number | Status ID ----------------------------------------------------------- 33 | 0a6e6ef0-a444-4b63-bd93-ae55fe8a3cee | 65001 44 | 5f699795-5119-4dcd-8b94-34f7056e732c | 65002 ... A history calculation (history object) In this example I am getting the latest event of each form - RepairForm.history.all()\ .values('return_number').annotate(latest_event_date=Max('history_date'))\ .order_by('return_number') Return Number | latest_event_date ----------------------------------------------------------- 0a6e6ef0-a444-4b63-bd93-ae55fe8a3cee | 7/27/2018 5f699795-5119-4dcd-8b94-34f7056e732c | 8/1/2018 ... I feel like this should be possible to do in one query though no? One query that outputs something like this: User ID | Return Number | Status ID | latest_event_date ------------------------------------------------------------------------------ 33 | 0a6e6ef0-a444-4b63-bd93-ae55fe8a3cee | 65001 | 7/27/2018 44 | 5f699795-5119-4dcd-8b94-34f7056e732c | 65002 | … -
how to use annotate to sum up all rows and get the avg? django
I was googling about this and there is a simplier way which uses Cast but then thing is I believe that's for django 2.0 that mine is django 1.9 I found a post and I tried it, it doesn't really work for me though. Let's say I have a model with value and max fields. I want to get the sum of all value and max then divide them to get the average. What I did just gets one row and return the avg of the row, can someone let me know what I have been doing wrong here? model_calcuation = Model.objects.filter().annotate( sum_score=Sum('value', output_field=FloatField()), sum_max=Sum('max', output_field=FloatField()) ).annotate( avg=F('sum_score') / F('sum_max') ) Thanks in advance for any help -
Trying to build a purchase order app
I've been working on a Purchase Order app but I'm getting a little confused how I'm going to put it all together. I have 3 models - class PurchaseOrder(models.Model): po_number = models.IntegerField(default=get_po_number, unique=True) po_date = models.DateField() invoice_number = models.ForeignKey(Invoice, on_delete=models.CASCADE) .... class PurchaseOrderItem(models.Model): po_number_fk = models.ForeignKey(PurchaseOrder, on_delete=models.CASCADE) qty = models.IntegerField() unit = models.CharField(max_length=100, blank=True, null=True) description = models.CharField(max_length=255) unit_price = models.DecimalField(max_digits=6, decimal_places=2) amount = models.DecimalField(max_digits=6, decimal_places=2) class PurchaseOrderTotal(models.Model): po_number_fk = models.ForeignKey(PurchaseOrder, on_delete=models.CASCADE) subtotal = models.DecimalField(max_digits=6, decimal_places=2) tax = models.DecimalField(max_digits=6, decimal_places=2, default="7.82") shipping = models.DecimalField(max_digits=6, decimal_places=2) other = models.DecimalField(max_digits=6, decimal_places=2) total = models.DecimalField(max_digits=6, decimal_places=2) the first (PurchaseOrder) holds information about the purchase order itself. ie. what the invoice number is, the vendor, etc. the second (PurchaseOrderItem) lists items in the purchase order to purchase the third (PurchaseOrderTotal) totals up the amounts from the items and adds tax etc. (I may not need this model.. I can probably put this info in the first model?) Does it look like I'm going about this in the right way or should I take away the third model and put those fields from the third model into the first model? How do I total up all prices for all items? I'm sure I'll need to … -
django how to add to my model a field list of its own model?
I am making a model, where will represent a product but I want to add a field with complementary_products, that I want to make it a list of product. for example, id: 1 product: dr pepper complementary_products [chips, hotdogs] id: 2 product: laptop complementary_products" [mouse, usb_cable] id: 3 product: chips complementary_products [dr pepper, hotdogs] I was trying many to many, but when I start adding prodcuts in the admin page, keeps appending, if I add 3 items, the last one will have all the first ones =( class ProductModel(models.Model): product_name = models.CharField(max_length=200) complementary_products = models.ManyToManyField("self", blank=True) if I use ForeingKey, I can only set to just one item =( complementary_products = models.ForeignKey("self", on_delete=models.CASCADE, default=None, blank=True) any recommendation on how can achieve this? thanks guys -
Info Window doesn't display
In spite of the fact that this question has been asked on Stackoverflow multiple number of times, I haven't been able to implement a working solution to my problem. I create an array for each parameter associated with a location. My intention is to declare these variables as global variables. var locationid = [] var latitude = [] var longitude = [] var observationdate = [] Then I loop through a datadump dictionary object which creates a row in the database for each location on the map with the values in columns being the values of parameters like longitude, latitude etc. {% for data in datadump %} locationid.push('{{data.locationid}}'); latitude.push('{{data.latitude}}'); longitude.push('{{data.longitude}}'); observationdate.push('{{data.observationdate}}'); {% endfor %} Next I loop through the database to create a marker at each location and also icon with a .svg static file for all locations. {% for data in datadump %} var latLng = new google.maps.LatLng('{{data.latitude}}','{{data.longitude}}'); var icon = { url: "{% static 'darkskymap/img/rocket-15.svg' %}", // url scaledSize: new google.maps.Size(20, 20), // scaled size }; marker = new google.maps.Marker({ position: latLng, map: map, title: '{{data.locationid}}', label: '{{data.observationdate}}', icon: icon }); {% endfor %} Then I declare an infowindow variable and assign it a text content. var infowindow … -
Redirect Json data to another view
I have a form where the user submit a code, after this I have a function that receive this code as parameter and make a consult on an API. The API returns a JSON data. And I would like to show this data that I received on a new page. How can I pass this JSON data to another view and render it? Here is my class and json_data contains my json response class IndexPageView(FormView): template_name = 'home.html' form_class = StudentVerificationForm success_url = reverse_lazy('core:home') def form_valid(self, form): student_enrollment_number = form.cleaned_data['enrollment_number'] json_data = student_exists(student_enrollment_number) return redirect('some-view') -
Style.css sometimes works sometime does not in django
So I am writing some simple web app, the project is here https://github.com/Aquakor/django-web-app. The problem is whenever I load index page style.css does not apply styles. In the console there is no 404 errors, so django finds the file. I tried many things like changing socialmedia app name to another with no success. I tried to clone the project and rerun everything, no success. I wrote django app using the intro tutorial, I remember the style.css worked there. I copied base.html, base_index.html to the tutorial app. I was testing this with background: green; applied to body. At first it worked, then I was checking what were the differences in tutorial app and my project. To be honest I could not find anything, then for some reason I decided to rerun the tutorial app again and the green background dissapeared... I also remember in the early stages of my project the style.css worked, I did git checkout to the first commit and style.css didn't work... I don't know if I'm a vegetable but I can't figure this out. I use anaconda3 environment with packages: certifi==2018.4.16 Django==2.0.7 psycopg2==2.7.5 pytz==2018.5 wincertstore==0.2 Python version: 3.7.0 (default, Jun 28 2018, 08:04:48) [MSC v.1912 64 bit … -
Why is apache not blocking this SQL injection vulnerability
I've got a Django/Apache/mod_wsgi stack, and I'm trying to isolate and remove a potential SQL injection vulnerability that an automated scan has thrown up. The scan's identified a potentially vulnerable URL: http://example.com/admin/ This returns an unexpected empty response if the request params include SQL injection patterns, e.g: curl -I "http://example.com/admin/?username=';SELECT%20pg_sleep(3);--" curl: (52) Empty reply from server In fact, through testing I've found that the issue seems specific to the presence of the postgres function call pg_sleep(), i.e. you can get the same empty response with either: curl -I "http://example.com/admin/?something=pg_sleep(3)" curl -I "http://example.com/admin/?something=pg_sleep()" but not with (for example): curl -I "http://example.com/admin/?something=sleep()" curl -I "http://example.com/admin/?something=pg_sleep" curl -I "http://example.com/admin/?something=now()" In an attempt to mitigate, I've blocked external access to the /admin section by IP address, through adding the following to the apache VirtualHost: <Location /admin> Require ip ***.***.***.*** </Location> This works as expected for all 'normal' URLs, e.g: curl -I "http://example.com/admin/" HTTP/1.1 403 Forbidden But it's still returning an empty response for the troublesome URL: curl -I "http://example.com/admin/?username=pg_sleep()" curl: (52) Empty reply from server The fact that it seems specific to the presence of the string pg_sleep() suggests, I'm guessing, that this is indeed somehow bypassing - or not reaching - the <Location> … -
Django: default user model RunTimeWarning about naïve DateTimeField
All my models except my User model inherit from this model: class BaseModel(models.Model): created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) class Meta: abstract = True Whenever a user signs-up, I get the following warning: RuntimeWarning: DateTimeField User.date_joined received a naive datetime (2018-07-04 06:38:11.288567) while time zone support is active. Since I don't control the User creation process (I'm using the default user model supplied by Django), I can't figure out how to solve this. -
Django Template Placeholders
In Django I want to make an app that handles a websites static pages. Things like about-us, privacy policy etc. The sort of pages which might be updated once every few months but not regularly. I want the user to be able to select a template they want to use and then be able to enter the content in to fields. I don't want these pages just to be a long block of text from a WYSIWYG editor. Using Django templates is there a way to indicate that there should be content going in this section but having this in multiple places of the template? Similar to how Django CMS placeholders {% placeholder %} work but be able to define what field (TextInput, TextArea etc) I want to be present in the admin when creating the page? I can't think of a way of doing this cleanly and can't see any apps online that offer this. -
Django App Not Writing Any Records to DB
I'm using this script https://github.com/jsfenfen/990-xml-database. This script loops through a large volume of XML files, then writes the contents to a database. I run the command $ python manage.py load_filings 2017 And the script immediately says it's completed, as in the photo below: I know that the database connection works properly, because it's creating the 180 or so tables in the database. However, all tables are blank. Given that there's no error message, what can I post here or research to better identify the problem? (Complete Python/Django newbie) -
Are Django SECRET_KEY's per instance or per app?
This question asks about the purpose of the Django SECRET_KEY value. One of the answers to that question stated "It needs to have a cryptographically strong amount of entopy(sp) (hard for computers to guess) and unique between all Django instances." This is a bit ambiguous: if I say for example have a single Django application deployed to multiple web servers behind a load balancer, should each have it's own distinct SECRET_KEY, or should the SECRET_KEY be shared amongst all instances? -
Providing extra data to Django admin inline form
I have a model IpList, which contains groups of users or just simple users. Now I want to show all IpLists related to user in inline form. But I can't figure out how can I display in those inline form all users from related groups. Here is my model: class IpList(models.Model): name = models.CharField(max_length=256, unique=True) description = models.TextField(blank=True) user = models.ManyToManyField(User, blank=True) group = models.ManyToManyField(Group, blank=True) For example, I have 1 user called 'MyUser' and 1 group called 'MyGroup', which contains 'MyUser'. Now I'm creating 2 IpLists: 'ListOne' with 'MyUser' and 'ListTwo' with 'MyGroup'. Then I'm going to my inline form for user 'MyUser' and there is only 'ListOne' because of queryset. So, the question is: how can I extend queryset or inline form data to display there 'ListTwo' too (because that list contains 'MyUser' too, but with group relationships)? I know, I can use signals and create relations IpList-User in change_m2m after adding/removing groups but I don't want to do it. Here is my UserAdmin: class IpListInline(admin.TabularInline): model = IpList.user.through extra = 0 verbose_name = 'IP list' verbose_name_plural = 'IP lists' fields = ('name', 'description') readonly_fields = ('name', 'description') can_delete = False class UserAdmin(BaseUserAdmin): add_form = UserAdminAddForm list_display = … -
django-import-export 404 error when importing via admin - no slash in url?
My set up looks like this, running Django 2.0.7, Python 3.7.0 and django-import-export 1.0.1 class SiteGradeResource(resources.ModelResource): class Meta: model = SiteGrade @admin.register(SiteGrade) class SiteGradeAdmin(ImportExportModelAdmin): resource_class = SiteGradeResource I can use the admin interface to export successfully from the SiteGrade model, but when I try use the Import button, I get a response code 404 because it couldn't find a {model}/NULL url: The current path, admin/data/sitegrade/import/NULL, didn't match any of these. This is with APPEND_SLASH = False in settings.py. When I try to run it with APPEND_SLASH = True, it gives me an error about the url not ending in a slash RuntimeError: You called this URL via POST, but the URL doesn't end in a slash... Am I doing it wrong or is this a django-import-export bug? -
Django:Table 'movies.main_movie_country_district' doesn't exist"
I can create the 'Country' item in the admin, but when deleting it, the following error occurs: The country model: class Country(models.Model): country = models.CharField(max_length=128, null=False, blank=False, unique=True) extra0 = models.CharField(max_length=256, null=True, blank=True) class Meta: db_table = 'country' verbose_name_plural = 'countries' ordering = ['country'] def __str__(self): return str(self.country) The project structure is below: The table name should be 'country' in my movies database, and I can see this in MySQL command line client. Why it searches table 'main_movie_country_district' when deleting? -
The given username must be set ( when trying to register an account )
I'm trying to create a UserRegister form using a ModelForm and save the given email as username to be used to log in.. But, I get the error The given username must be set, as you see in the views.py I've tried to validate the password confirmation manually. by taking values of the input in HTML and add an IF statement to the view trying to make sure they are the same. here are my codes: forms.py class RegisterForm(forms.ModelForm): username = forms.CharField( widget=forms.EmailInput( attrs={ 'class': "form-control", 'placeholder': "Email - البريد الإلكترونى", } ) ) password = forms.CharField( widget=forms.PasswordInput( attrs={ 'class': "form-control", 'placeholder': "Password - كلمة المررو", } ) ) class Meta: model = User fields = ['username', 'password'] views.py def register(request): if request.method == 'POST': register_form = RegisterForm(request.POST) if register_form.is_valid(): user_name = request.POST.get('id_username') password1 = request.POST.get('id_password') password2 = request.POST.get('password2') if password1 != password2: messages.error(request, 'كلمة السر غير متطابقة') else: user = User.objects.create_user(username=user_name, email=user_name, password=user_name) user.save() return redirect('home') else: register_form = RegisterForm() context = { 'register_form': register_form, } return render(request, 'auths/register.html', context) and finally here is the HTML code part that belongs to the form <form role="form" class="login-form" method="POST"> {% csrf_token %} <div class="form-group"> <div class="input-icon"> <i class="icon fa fa-user"></i> {{ … -
Query Database - Django
I'm building a small app using Django Rest Framework which is intended to pull data from an existing transactional database, display the data, and allow users to add information related to that data which will be persisted in the Django application's database. I'm unsure, however, how to display information from another transactional DB, which I do not want to persist in my Django application's database, in a list in my app. I was able to successfully display information which is persisted to the Django apps transactional DB by doing queryset = Model.objects.all(), however, once again, I want to do this for a random query instead of a model. Or to put it another way, can I define a model, which is a representation of a query (a select from many tables of another transactional DB which I do not want to persist in the transactional DB of my Django app), which I can use to display information on the UI? Thank you in advance. -
Django: Render html tag inside bootstrap modal
I'm trying to add markdown to my Django app and it works, but not when the test is displayed inside a bootstrap modal. I use markdown2 to render the text and a custom templatetag like this: {{ issue.description | markdown | safe }} Any suggestion about how to do it work inside a modal? -
Django with MySQL backend - group by time range
I've got this simple model: models.py class Ping(models.Model): online = models.BooleanField() created = models.DateTimeField(db_index=True, default=timezone.now) def __str__(self): return f'{self.status}, {self.created}' It gives me the following results: mysql [lab]> SELECT * FROM myapp_ping; +----+--------+----------------------------+ | id | online | created | +----+--------+----------------------------+ | 1 | 1 | 2018-08-02 13:34:09.435292 | | 2 | 1 | 2018-08-02 13:35:09.520200 | | 3 | 0 | 2018-08-02 13:36:09.540638 | | 4 | 0 | 2018-08-02 13:37:10.529783 | | 5 | 1 | 2018-08-02 13:38:09.779012 | | 6 | 1 | 2018-08-02 13:39:09.650365 | | 7 | 1 | 2018-08-02 13:40:09.625543 | | 8 | 1 | 2018-08-02 13:41:09.892196 | | 9 | 1 | 2018-08-02 13:42:09.802186 | | 10 | 1 | 2018-08-02 13:43:09.864551 | | 11 | 1 | 2018-08-02 13:44:09.960962 | | 12 | 1 | 2018-08-02 13:45:09.891947 | | 13 | 0 | 2018-08-02 13:46:09.141727 | | 14 | 0 | 2018-08-02 13:47:09.142030 | | 15 | 0 | 2018-08-02 13:48:09.160942 | | 16 | 0 | 2018-08-02 13:49:09.152879 | | 17 | 0 | 2018-08-02 13:50:09.280246 | | 18 | 1 | 2018-08-02 13:51:09.363184 | | 19 | 1 | 2018-08-02 13:52:09.405863 | | 20 | 1 | 2018-08-02 13:53:09.403251 … -
Django project giving me TypeError: combine() takes at most 2 arguments (3 given) when deployed
I have deployed my django project on digitalocean and it was working fine so far, until I made some changes to the way I was storing datetimes in my databases. I made them time-aware (before they were naive). Eventually, I ironed out all the bugs and my times were aware, and the project was working fine until I pulled the changes to my production server and when I tried to deploy it, it gave me the following error: TypeError: combine() takes at most 2 arguments (3 given) on this line: start_time_in_local_time = datetime.datetime.combine(date, start_time, time_difference) For context, this error happens every time I attempt to schedule a lesson with another user. I receive the timings and timezone information from the user, and I am trying to store the starting and ending times of that lesson in my database. Here's the code: def error_check_and_save_lesson(request, lesson, context): # Get lesson timezone when (re)scheduling lessons minutes_offset = request.POST.get('timezoneInfo','') minutes_difference = int(minutes_offset) time_difference = datetime.timezone(datetime.timedelta(minutes=minutes_difference)) # Get lesson name when (re)scheduling lessons if not request.POST['name']: context['name_error'] = True else: lesson.name = request.POST['name'] # Get lesson location when (re)scheduling lessons if not request.POST['location']: context['location_error'] = True else: lesson.location = request.POST['location'] # Get lesson date when … -
Session id & csrftoekn issue
I have an API to design that requires the following functionality: STEP 1. GET /login/ should return response with csrftoken & session id. STEP 2. User can perform login by sending POST /login/ with csrftoken & session id as headers and csrfmiddlewaretoken along with the form parameters. STEP 3. Once successfully logged in, the POST /login/ response will contain a new session id that is to be send along the headers for future requests and proves to the server that the user is logged in. STEP 4. For other API POST apps the session id obtained in the step 3 and the csrftoken obtained in step 1 are to be used. I am having trouble implementing this behavior. Django does not return a session id for GET /login/, so I achieve this by having the following in my /login/ views.py: if hasattr(request, 'session') and not request.session.session_key: request.session.save() request.session.modified = True This successfully returns a session id for GET /login/ and later when I call authenticate(user, passwd) for POST /login/ the session id is reset. Now, my questions: What is the proper way to enable session id before authentication? and making sure the session id resets on successful authentication and remains … -
Tutorial Request: Deploying a GitHub Django App on Azure
I'm completely new to Python/django, but I have a GitHub app that I'd like to clone in Azure. I can't run it in my company's IT environment. I started by creating a Django + PostgreSQL app in Azure. Then I went to command line, thinking that I could try something like "python -m pip install git," then "git clone http://xxxx", but I'm getting this error on the first command: Downloading/unpacking git Could not find any downloads that satisfy the requirement git Cleaning up... No distributions at all found for git Storing debug log for failure in D:\home\pip\pip.log