Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - unable to publish Linux server
First of all, I can access the webpage from local host. But if I were to access it from outside machines, I am unable to access the page. This is what I get when I run python manage.py runserver 0.0.0.0:8000 System check identified no issues (0 silenced). September 18, 2018 - 05:45:59 Django version 2.0.6, using settings 'sage.settings' Starting ASGI/Channels version 2.1.2 development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. 2018-09-18 05:45:59,176 - INFO - server - HTTP/2 support not enabled (install the http2 and tls Twisted extras) 2018-09-18 05:45:59,179 - INFO - server - Configuring endpoint tcp:port=8000:interface=0.0.0.0 2018-09-18 05:45:59,180 - INFO - server - Listening on TCP address 0.0.0.0:8000 Lets assume that my IP address for my Linux server is 70.111.222.333. Then I should be able to access it from other computers by typing http://70.111.222.333:8000 on a browser. But it doesn't work. In my settings.py, this is how it looks right now: # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['', '*'] The Linux server has a few virtual machines installed, and I've correctly set up fort forwarding for my application virtual machine, port 8000, Local IP 192.168.1.100. And yet, … -
Python coverage does not see config file
I am running python coverage for Django unit tests in parallel mode: coverage run --source='.' --concurrency=multiprocessing manage.py test --parallel It is complaining: Options affecting multiprocessing must be specified in a configuration file. But I have .coveragerc file in the same directory from which I start coverage with the following content: [run] branch = True concurrency = multiprocessing Tried to specify --rcfile option for coverage run, that did not help. What am I missing? Thank you! -
How to implement multiple databases in django like I want to use sqlite3, the default database of django for authentication and later part on mongo_db
I want mongo db to be used in my project with respect to the sqlite3. Because removing whole sqlite3 causes me to write the authentication part in mongo db as well. So i want to implement authentication using sqlite3 and profile using mongodb -
If I extend django 'Sites' model, will other features work for my newly created model?
If I extend Django Sites model, will feature like CurrentSiteManager or get_current().domain work for that model? -
Python create "secret id" for usernames
I have a model: Target(Model: name = CharField() user = ForeignKey(User) and also Hunter(Model): club = CharField() Hunters should not be able to see the name of the target. Thus I want them to see a secret and anonymous name. Perhaps something like John Smith => Ao3n(Sn331 I tried using hashlib to do this: hashlib.md5("targetEmail@hunterClubName".encode()).digest() but then there is no way to reverse the hash to find out who the Target actually is. What would be a better way to achieve this? -
Django NoReverseMatch with keyword argument not found
thank you for your help. long store short, here is my git repo. https://github.com/nelsonyan/track I have the following error message while clicking on the href in line 22 of employee_list.html. It is supposed to take me to the employee_detail.html to update but gave me the following error about 'track_delete' url tag... The two apps (report, employee) have foreign key associated, but I don't see why the update function of employee app is related to the delete function of report app. Can any django expert help me out? GET Request URL: http://127.0.0.1:8000/employee/update/7/ Django Version: 2.0.5 Exception Type: NoReverseMatch Exception Value: Reverse for 'track_delete' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['report\/delete\/(?P[0-9]+)\/$'] Exception Location: C:\Users\Nelson\Anaconda3\envs\mydjangoenv\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 632 Python Executable: C:\Users\Nelson\Anaconda3\envs\mydjangoenv\python.exe Python Version: 3.6.6 In detail, I am trying to create a site to track art project and display company staff info. The report app works well. It can create/display/update/delete report record. I am simply duplicating the update function to the employee app but have the above problem. It is probably the models of report app has two foreign keys of the same class from employee app's models ('employeelist'). that is why the two apps are associated but … -
django test override_settings at class-level overwrites settings before they can be initialized
Unsure if I've stumbled on a bug. I am using @override_settings in my tests and observe a different behavior annotating this on my test classes vs test methods. Specifically if I put the annotation on the class, the first time I run through the django.conf.LazySettings.__getattr__(), self._wrapped already returns my initialized override, and therefore the self._setup() is never called and the rest of my settings are not loaded. e.g.: @override_settings(FOO="mock_val") #prevents regular settings class FooTests(TestCase): @override_settings(FOO="mock_val") #allows regular settings test_foo(self): LazySettings source: https://github.com/django/django/blob/master/django/conf/init.py -
Is it possible to deny access to copied password field in database?
My Django app password in database looks like this: pbkdf2_sha256$100000$XXXXXXXXXX$XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX But if I duplicate it to another user, I could log in to that user's account. Assuming a database breach or some kind of injection, can I detect if password was somehow duplicated/copied so that I can deny access to the account or alert admins? -
Django; django.db.utils.OperationalError: FATAL: no pg_hba.conf entry for host, user, database
I'm a beginner and I've been creating a Django project. I'm trying to switch sqlite3 db to postgresql. But when I do make migrations, this error occurred. django.db.utils.OperationalError: FATAL: no pg_hba.conf entry for host, user, database I searched about this error. And some people checked pg_hba.conf file, but I have no idea where this file is. Also when I created project before and did the same thing, there's no this error. Why is this error happening this time? What is the cause? How can I fix this error? -
Django background can not display some fields
enter image description here enter image description here Hey, brother, can you tell me how the next field pub_date and mod_date don't show up in the Admin backstage? -
how to insert a dataset into a text file using python?
How to insert a dataset like 'abdcef' into text file by replacing the data in the text file. Can anyone please help me -
'why is coming " can not import name 'path' in django latest version
I am a beginner at Django...When I am giving python manage.py runserver or any python command then a terminal output is: from django.conf.urls import include, path ImportError: cannot import name 'path' -
Jquery Upload to Cloudinary only when submit button is clicked
I have a question regarding direct-image-upload to Cloudinary. After I select the file, it start uploading. I don't like this approach and I want that upload start just after i clicked on the submit button. Thank you. -
Django projects deployment choice
I have one django project that use the mysql as database. Before deploying, the mysql is the local database as following in the setting. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'xxx', 'USER': 'root', 'PASSWORD': 'xxxx', 'HOST': 'localhost', #'PORT': '3306', } } I have successfully deployed the projects on heroku, but it keeps show that the "2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)" since the setting is the local mysql and the view.py contains function that import local database. I still cannot figure out how to have the website to connect to this database. So, my question is: which server is the best choice to deploy online for my case? Should I still choose heroku or others that is compatible to mysql database? Thx a lot! -
Play a previously uploaded mp3 in a django 1.10 template
Ok, the basics. mate desktop on linux mint, Python 3.5.2 django 1.10, not that I think any of those details is going to be relevant. I think I'm doing something very basic wrong with my html. I can't play a local mp3 file, either directly hard coded, with either an absolute path or a relative path, or by passing the path to the file via a method that works for the rest of my data. I can play an mp3 from the net, with this in my template` <p> <audio controls src="https://soundbible.com/mp3/Tyrannosaurus%20Rex%20Roar-SoundBible.com-807702404.mp3"> </audio> That works fine. This same template can take data entered in my form and pass it to the template to be displayed in the browser via: <p style="margin-left: 40px">{{ post.published_date }}</p> The {{ post.published_date }} does retrieve the data it's supposed to, in fact everything else works fine, dozens of inputs work exactly as I expect them to. So likely not problems with my models or forms. The file upload I use in the form seems to be working fine, as I can manually confirm the file is there within the folder structure I've specified. documents/Year/month/day/file.mp3. I can confirm that post.docfile (method I use to grab the … -
How do I show the results of my [Django] model in [HTML] from a [PostgreSQL] database?
I am developing a web application with Django and PostgreSQL support. I am using Psycopg2 to connect with my PostgreSQL database. I am attempting to list all of the tables in my database on my Home.html document. I am having trouble showing this in the Home.html document. Below I have included my code. models.py from django.db import models import psycopg2 # Create your models here.def __init__(self, db='giquery-data'): class Tables(models.Model): conn = psycopg2.connect("dbname='giquery-data' user='postgres' host='localhost' password='admin'") cur = conn.cursor() # """SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' AND TABLE_SCHEMA='public'""" cur.execute("SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' AND TABLE_SCHEMA='public'") rows = cur.fetchall() views.py from django.shortcuts import render from django.http import HttpResponse from .models import Tables from django.template import loader # Create your views here. def index(request): all_tables = Tables.rows template = loader.get_template('tablesearch/home.html') context = { 'all_tables': all_tables } return HttpResponse(template.render(context, request)) Home.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <ul> {% for rows in all_tables %} <li> {{ rows.table_catalog }} - {{ rows.table_name }} Test </li> {% endfor %} </ul> </body> </html> Currently, my results look like: How can I show the names of the database tables on Home.html? -
Serializers in Foreign Key Django
i need to get information from Reservation, ReservationDetails and Product, but just get Reservation and ReservationDetails i have 3 models class Reservation(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) userReservation = models.ForeignKey(User, on_delete=models.CASCADE, default=1) dateStart = models.DateTimeField(null=False, blank=False, default=datetime.now) dateFinish = models.DateTimeField(null=False, blank=False, default=datetime.now) date_Created = models.DateTimeField(auto_now_add=True) date_Modified = models.DateTimeField(auto_now=True, db_index=True) def __str__(self): return str(self.id) class DetailsReservation(models.Model): Reservation = models.ForeignKey(Reservation, blank=False, on_delete=models.CASCADE, null=True, related_name='reservation_details') product = models.ForeignKey(Product, blank=False, on_delete=models.CASCADE, null=True, related_name='products_reservation') Quantity = models.IntegerField(null=False, blank=False, default=0) userbyReserva = models.ForeignKey(User, editable=False, on_delete=models.CASCADE, default=1) class Product(models.Model): product_Description = models.CharField(max_length=255) Quantity = models.IntegerField(null=False, blank=False, default=0) Quantity_Max_Reservation = models.IntegerField(null=False, blank=False, default=0) product_Comments = models.CharField(max_length=255) size = models.CharField(max_length=10, null=True) product_Status = models.BooleanField(default=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, related_name='products') date_Created = models.DateTimeField(default=datetime.now, blank=True) date_Modified = models.DateTimeField(default=datetime.now, blank=True) And i tried to create serializers class ReservationDetailsSerializers(serializers.ModelSerializer): products = serializers.PrimaryKeyRelatedField(queryset=Product.objects.all(), required=False) class Meta: model= DetailsReservation fields = ['Reservation', 'Quantity', 'userbyReserva', 'products'] class ReservationDetailsListSerializer(serializers.ModelSerializer): reservation_details = ReservationDetailsSerializers(many=True) class Meta: model = Reservation fields = ['id', 'userReservation', 'dateStart', 'dateFinish', 'reservation_details'] but the response does not show this field [ { "id": "6d87ba1c-61bc-41bd-80c8-31a51df8d32f", "userReservation": 1, "dateStart": "2018-09-16T17:19:34-05:00", "dateFinish": "2018-09-16T17:19:35-05:00", "reservation_details": [ { "Reservation": "6d87ba1c-61bc-41bd-80c8-31a51df8d32f", "Quantity": 1, "userbyReserva": 1 >>"here should show this information product" } ] }, { "id": "0ed26395-2579-4c40-9a63-460f5095ac51", "userReservation": 2, "dateStart": … -
I have a Kivy GUI started by a Django project. But it does not run on an Apache 2 server (with mod_wsgi)
I'm currently working on a Django project that runs on a Raspberry Pi with a touchscreen. A Kivy GUI is displayed on the touchscreen and can be updated by a webinterface provided by Django. Interactions with the touchscreen can also be seen by the website user. The Kivy App (kivy.app.App) is started within a thread class SimpleKivyThread(threading.Thread): def __init__(self): Thread.__init__(self) self.app = SimpleApp() def run(self): self.app.run() from the __init__.py module of my Django App. So if I use the python3 manage.py runserver --noreload command, the project runs just fine, a communication between the Django App and the Kivy App is possible. I have to use the --noreload flag to suppress automatic code reloading because this would duplicate the GUI with the effect that the Django App has no access to any of the produced GUIs. But if I want to use it on an Apache 2 server with mod_wsgi on my Raspberry Pi (with Raspbian), the error.log shows at first this: [Tue Sep 18 01:08:27.963060 2018] [mpm_prefork:notice] [pid 440] AH00169: caught SIGTERM, shutting down [Tue Sep 18 01:08:28.111606 2018] [mpm_prefork:notice] [pid 976] AH00163: Apache/2.4.25 (Raspbian) mod_wsgi/4.5.11 Python/3.5 configured -- resuming normal operations [Tue Sep 18 01:08:28.111883 2018] [core:notice] [pid 976] … -
Django strange DecimalField validation
I got validation error when it shouldn't be raised. Here is the example from django.db.models import DecimalField f = DecimalField(max_digits=9, decimal_places=3) # got validation error here # `Ensure that there are no more than 3 decimal places` f.clean(value=12.123, model_instance=None) # returns Decimal('12.1230000') f.to_python(12.123) # this is absolutely fine f.clean(value=123456.123, model_instance=None) # returns Decimal('123456.123') f.to_python(123456.123) Apparently, django DecimalField uses wrong implementation of to_python which return excessive amount of trailing zeros at the end, and then validation fails. What could be done with that? -
Django form initial pass a list to one attribute
I met an issue when I want to pass a list of value to one attribute during initial the form. The whole process of what I am doing is: 1. User defines a number N. 2. I display N text field. 3. User fills in data and I store in the database. 4. User wants to modify the data -> which is the issue I have when. I want to initial the form with current data. Here is my model.py class PageComponent(models.Model): componentName=models.CharField(max_length=50,null=True, verbose_name="Name") type = models.ForeignKey(Type, on_delete=models.CASCADE) user = models.ForeignKey(AS_User, on_delete=models.CASCADE, editable=False) page = models.ForeignKey(CommunityPage, on_delete=models.CASCADE, editable=False) STATUS = ( ('a', 'Activated'), ('d', 'Deactivated'), ) componentStatus=models.CharField( max_length=1, choices=STATUS, blank=False, default='d', help_text='the current status of the page component', editable=False ) textContent=models.TextField(max_length=10000, help_text="Enter a description for your component", null=True, blank=True) photoContent=models.ImageField(upload_to=component_directory_path, null=True, blank=True, verbose_name="Photo") videoContent=models.FileField(upload_to=component_directory_path, null=True, blank=True, verbose_name="Video") def __str__(self): return self.componentName class PageComponent_SeasonalText(models.Model): pageStextComponent = models.ForeignKey(PageComponent, on_delete=models.CASCADE) seasonalText = models.CharField(max_length=10001) Here is my form.py class SeasonalTextForm(forms.Form): componentName = forms.CharField(label=_('Enter title'),max_length=40) def __init__(self, *args, **kwargs): seasonTexts = kwargs.pop('extra') super(SeasonalTextForm, self).__init__(*args, **kwargs) # self.cleaned_data = {} for i in range(0, seasonTexts): field_name = 'seasonText_%s' % (i,) self.fields[field_name] = forms.CharField(widget=forms.Textarea(attrs={'rows':10, 'cols':51})) #set field label as placeholder for every field for field in self.fields.values(): … -
Django - Boolean updated on web view but not when exported
Depending on certain conditions on the models.py, I would like to have the ABC BooleanField to be ticked (green check) or unticked (red cross). This, I have done it without any problems; however, when I am trying to export (as a CSV or XLSX) that same dataset with the ABC BooleanField, the BooleanField is not updated according to the web view nor the models.py I have set. Could you please give me some guidance? The following are parts of the code: class something(models.Model) book = models.BooleanField(default=False) ... some code ... def bookcheck(self): if self.writingDate is not None: if self.publishDate is not None: self.book = True return True else: return False else: return False bookcheck.boolean = True -
Highlight untranslated Django strings
In my po file, some strings are translated, but others not: msgid "Hello there" msgstr "Hallo du" msgid "Goodbye" msgstr "" As is intended, this transparently falls back - I see Goodbye although no translated text is present. However, these strings can be overlooked easily (especially if the languages are quite similar). Is there a way I can add a note for untranslated strings, so that it shows up as UNTRANSLATED:Goodbye/UNTRANSLATED ? -
django models error when inputting form data
I am a beginner in django, and am having some trouble inputting form data to database. I am getting a TypeError at /Info/ Info() got an unexpected keyword argument 'email' when I feel I am doing it correctly Here is my models.py from django.db import models # Create your models here. class Info(models.Model): address = models.CharField(max_length=70) email = models.EmailField(max_length=32) My Views.py def Info(request): if request.method == 'POST': form = InfoForm(request.POST) if form.is_valid(): address = request.POST.get('address') email = request.POST.get('email') Facts = Info(email = email) Facts.save() else: form = InfoForm() return render(request, 'index/index.html', {'title': 'Info'}) def index(request): return render(request, 'index/index.html', {'title': 'Home'}) My Forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class InfoForm(forms.Form): address = forms.CharField() email = forms.EmailField() Thanks. Any help is appreciated. -
generate swagger api docs for custom views in django
I am developing a DJANGO app. I want to document all the APIs that I am implementing and hence using swagger to generate the API documentation. I am running into the following issues - I am not able to document the payload of custom POST methods. The output fields of GET request are also not available. Upon checking online I found that I will have to write custom views and custom serializers for the payload of POST and GET methods. Writing extra code just to generate documentation sounds cumbersome. Is there any better way? -
Django - What is conventional for handling multiple requests from a single form?
I may not have worded the question the best but what I would like to know is what would be a good/best way for handling multiple request possibilities from a template? For ex. I have a template that displays a form along with any attachments that are held in a separate table but directly relate to the current record. So I have a submit button for the form and I also have 2 other buttons that are for adding and deleting the attachments from the separate table. I have handled the adding of the attachment by utilizing the name attribute on the input tag. I initially thought of doing the same thing with deleting but I did not have a way of passing the ID of the record to the view function so I created a separate URL to process that request. The issue with this approach is that I can no longer pass the same form instance back to the user. Once the user hits delete it resets the form basically. Is it typical/preferred to create some URLs solely for processing requests? I have a feeling that the best answer would be to use AJAX requests but I am …