Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to log requests and responses in Django?
How can I log all my requests and responses (headers and body) in Django using a middleware? I'm using Django 2.2 with Django rest framework, so sometimes the requests and responses are original Django type, sometimes of drf. The app is served behind gunicorn. I've developed middleware but the main problem is I can't read request's body twice as it gives me error. -
PostgreSQL Db traffic encryption with Django
I am using Django 3.08 with a PostgreSQL 12 Remote server. I have searched the docs for Postgres and Django, but can’t find discussion of how/if Django encrypts the traffic between my app and the dB. It looks like to me that the traffic is encrypted using md5 encryption by default in PostgreSQL based on the settings in PostgreSQL,and sends it by tcp over port 5432. It is my understanding that md5 is no longer sufficient encryption. However PostgreSQL has supported scram-Sha-256 since PostgreSQL 10. Does anyone know or have a reference to where I can set my app to use the stronger encryption or is it all taken care of if I set all traffic on my site to use https in the settings.py file. Or, will Django use scram-Sha-256 if I just change the setting in PostgreSQL? -
how to set up Django translation on Heroku
help me, where am doing wrong my settings.py LANGUAGE_CODE = 'fr' # LANGUAGE_COOKIE_NAME = 'LANGUAGES' LOCALE_PATHS = (os.path.join(BASE_DIR, 'authentication/locale'),) LANGUAGES = ( ('fr', _('France')), ('en-us', _('English (US)')), ) my views.py def set_language(request): language = request.POST.get('language', settings.LANGUAGE_CODE) next_link = request.POST.get('next', "/") user_language = 'fr' translation.activate(user_language) request.session[translation.LANGUAGE_SESSION_KEY] = "fr" return redirect(next_link) on local environment it works fine but not working on heroku, please help. -
serializer.save() not saving data to admin database
So, i was making a simple Web app in which i would get in data from user using React JS Front-end Interface and Forms. Django stays in the background where i have made CRUD functions. My app lets user to create, edit, delete and view the data inputted. Edit and View work perfectly fine but create has been making a problem for me. There is no error in the browser console or django terminal but the React JS front-end change does not reflect in the Django Admin. Now, handleChange simply listens to the change made in the HTML form. Active Record is my current form in which new data is being added: handleChange(e){ var value = e.target.value; this.setState({ activeRecord:{ ...this.state.activeRecord, [e.target.name]:value } }) } handleSubmit() just connects my frontend submit button to Django's CRUD'S Create url. Finally, i set the current object state back to default. handleSubmit(e){ e.preventDefault() console.log('Item',this.state.activeRecord) var csrftoken = this.getCookie('csrftoken') var url = 'http://127.0.0.1:8080/DataCollection/create/' fetch(url,{ method:'POST', headers: { 'Content-type':'application/json', 'X-CSRFToken': csrftoken, }, body:JSON.stringify(this.state.activeRecord) }) .then((response)=>{ this.fetchTasks() this.setState({ activeRecord:{ id: "", full_name:"", age:"", gender:"", weight:"", height:"", salary: "", project_count: "", job_domain: "", experience: "", no_of_jobs:"", } }) }).catch(function(error){ console.log('ERROR',error) }) } handleSubmit() just connects my frontend submit button … -
django.db.utils.OperationalError: could not connect to server: No such file on Unix domain socket "/tmp/.s.PGSQL.5432"?
When i connect postgres database with Django, it gives me following error, screenshot attach init. when i use direct database name or user etc then this work fine but when i use through enviroment variable, it is not working. this is my setting.py file 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('DATABASE_NAME'), 'USER': os.environ.get('DATABASE_USER'), 'PASSWORD': os.environ.get('DATABASE_PASSWORD'), 'HOST': os.environ.get('DATABASE_HOST'), 'PORT': 5432 this is my .bash_profile enviroment variable export DATABASE_NAME='blog' export DATABASE_USER='bloguser' export DATABASE_PASSWORD='blog@123' export DATABASE_HOST='localhost' self.connection = self.get_new_connection(conn_params) File "/home/kamran/anaconda3/envs/DjangoEnv/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "/home/kamran/anaconda3/envs/DjangoEnv/lib/python3.8/site-packages/psycopg2/init.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/tmp/.s.PGSQL.5432"? -
Why is it suggested to use a different service to host static files (like nginx or apache) for django?
I've seen many questions on stackoverflow about handling static files in django during deployment. I saw that many answers said something like this - "With debug turned off Django won't handle static files for you any more - your production web server (Apache or something) should take care of that." Why can't we use the server hosting the django project to host the static files too? -
how should i import dataset into my django project and do my recommendatio system?
I am making movie recommendation system.All the things are done and for the recommendation part i am not so confident about datset. how can i use these datset or import it to my django project? -
Python, json object, issues with booleans value
i have a JSON object I want to post to a 3rd party API. I'm getting exceptions at all my boolean values. I'm not sure why. This is my object index_schema = { "name": "hotels-new", "fields": [ { "name": "HotelId", "type": "Edm.String", "key": true, "filterable": true }, { "name": "HotelName", "type": "Edm.String", "searchable": true, "filterable": false, "sortable": true, "facetable": false }, { "name": "Description", "type": "Edm.String", "searchable": true, "filterable": false, "sortable": false, "facetable": false, "analyzer": "en.microsoft" }, { "name": "Description_fr", "type": "Edm.String", "searchable": true, "filterable": false, "sortable": false, "facetable": false, "analyzer": "fr.microsoft" }, { "name": "Category", "type": "Edm.String", "searchable": true, "filterable": true, "sortable": true, "facetable": true }, { "name": "Tags", "type": "Collection(Edm.String)", "searchable": true, "filterable": true, "sortable": false, "facetable": true, "analyzer": "tagsAnalyzer" }, { "name": "ParkingIncluded", "type": "Edm.Boolean", "filterable": true, "sortable": true, "facetable": true }, { "name": "LastRenovationDate", "type": "Edm.DateTimeOffset", "filterable": true, "sortable": true, "facetable": true }, { "name": "Rating", "type": "Edm.Double", "filterable": true, "sortable": true, "facetable": true }, { "name": "Address", "type": "Edm.ComplexType", "fields": [ { "name": "StreetAddress", "type": "Edm.String", "filterable": false, "sortable": false, "facetable": false, "searchable": true }, { "name": "City", "type": "Edm.String", "searchable": true, "filterable": true, "sortable": true, "facetable": true }, { "name": "StateProvince", "type": "Edm.String", "searchable": … -
State management with Django
class MyModel(models.Model): STATE1 = 1 STATE2 = 2 STATE3 = 3 STATE_CHOICES = ( (STATE1,"state1"), (STATE2,"state2"), (STATE3,"state3"), ) . . state = models.PositiveSmallIntegerField(choices=STATE_CHOICES, default=1) def save(self): pass def method1(self): pass def method2(self): pass The thing I would like to do; if state1 to state2 trigger method1, if state2 to state1 trigger event2, state2 to state3 trigger method3 etc.. how do I code without using many "if statement"? I want to write clean code. Thanks for your help. -
Heroku: Python Django deployment suddenly failing
I deployed my app this morning all fine, it has been running for months, I have just tried to deploy a change to two HTML template (nothing else has changed in GIT). Heroku is suddenly failing with the below -----> Python app detected ! Requested runtime (python-3.6.10) is not available for this stack (heroku-18). ! Aborting. More info: https://devcenter.heroku.com/articles/python-support ! Push rejected, failed to compile Python app. ! Push failed I can't even see anywhere I've specified a python version in Django, not in requirements.txt, but nothing has changed in this respect for months on the apps? Any ideas greatly appreciated -
Django does not to save all Foreign Keys columns to model
I'm attempting to load an excel template to a Django model. One of the excelsheets is called DriverValue and contains a value column, and four ForeignKey columns (driver, scenario, dmo, and period). The first three ForeignKey columns(driver, scenario, dmo) were already there from the beginning of the project together with the value column. Then we started using the project and had users save tons of data to the database. Now we're trying to add the period column as a fourth ForeignKey column to the DriverValue model, and something weird occurs: while there are various rows that I expect to be saved from the excel to the model (namely one row for each unique value/period combination - see added excel picture of new template), Django only saves the first instance, e.g. the one where value = 10000 and period = 1. The rest is omitted. The new excel template looks like this: excel template new whereas the old one looks like this: excel template old Question: is there a way to add the period column to the Django model and have Django load the excel template correctly, without having to delete the database already in use? Already tried: I tried deleting … -
Django form validation fails when using second unmanged database / How to use 2nd DB for form validation?
I am using two databases in my django project: settings.py DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": os.path.join(BASE_DIR, "db.sqlite3"), }, "2ndDB": { "ENGINE": "sql_server.pyodbc", "NAME": "2nddb-sqldb", "USER": CRED["user"], "PASSWORD": CRED["password"], "HOST": "2ndserver-sqlsrv.database.windows.net", "PORT": 1433, "OPTIONS": {"driver": "ODBC Driver 17 for SQL Server",}, }, In my view I try to validate my form: views.py def registration(request): if request.method == "POST": form = RegistrationForm(request.POST, user=request.user.get_username()) if form.is_valid(): forms.py class RegistrationForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.form_method = "post" self.helper.add_input(Submit("submit", "OK")) class Meta: model = Registration fields = ( "uuid", "xyz", ) Which fails as it tries to validate the unique constraint of the pk of the model in the unmanaged db: models.py class Registration(models.Model): uuid = models.UUIDField(primary_key=True, verbose_name="UUID") class Meta: db_table = "xyz" managed = False It is pretty that it tries to access the primary db an obviously can not find the tabel. (Which is the error that I receive.) I know how to use the second DB when saving the form or making queries by using the "using" option. I can't figure out how to make this work with the validation though. -
How to pass value in URL in django-restframework
I have been following below tutorial and it's just showing value in POSTMAN https://dzone.com/articles/create-a-simple-api-using-django-rest-framework-in Code: @api_view(["POST"]) def IdealWeight(heightdata): try: height=json.loads(heightdata.body) weight=str(height*10) return JsonResponse("Ideal weight should be:"+weight+" kg",safe=False) except ValueError as e: return Response(e.args[0],status.HTTP_400_BAD_REQUEST) I want to use GET method instead of POST and pass value of height in url, example: http://127.0.0.1:8000/IdealWeight/height=20 and result should be visible in the form of JSON -
How do I use a 'q' to call an API and get a response in Django views?
I'm trying to query this api and get a response but I'm obviously not doing it correctly as i know its not as simple as this. from django.shortcuts import render def home(request): response = request.GET["https://api-adresse.data.gouv.fr/search/?q=8+bd+du+port"} return render(request, "home.html", {'response': response}) I would like to be able to give an address to the API ie: "8 Boulevard du Port 80000 Amiens" and get the associated information about it. ie: gps coordinates I can't seem to find information on how to make this kind of request and handle the response using views in django. -
Syndication feed framework: 'NoneType' object has no attribute 'category'
Django 3.0.8 feeds.py class RssFeed(Feed): title = "Pcask.ru" link = get_site_address() description = "News" def items(self): # All evergreen posts and fresh news (just exclude old news). pass # Breakpoint return Post.published.exclude(Q(tags__name__in=[SPECIAL_TAGS.NEWS.value]), Q(updated__gte=timezone.now()-timedelta(days=NEWS_LIFESPAN)))[:NUMBER_OF_ITEMS] # Breakpoint def item_title(self, item): return item.title def item_description(self, item): return item.description def categories(self, item): return (item.category.title,) feed_copyright = 'Все права защищены (c) {}, {}'.format(timezone.now().year, get_site_address()) def item_enclosures(self, item): featured_image = item.get_featured_image() pass def item_enclosure_mime_type(self, item): featured_image = item.get_featured_image() pass def item_pubdate(self, item): return item.created def item_updateddate(self, item): return item.updated urls.py from feeds.feeds import RssFeed urlpatterns = [ path('rss/', RssFeed(), name="rss"), Problem When I load http://localhost:8000/rss/, I get this: Environment: Request Method: GET Request URL: http://localhost:8000/rss/ Django Version: 3.0.8 Python Version: 3.8.0 Installed Applications: ['django_cleanup.apps.CleanupConfig', 'admin_aux', 'images.apps.ImagesConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.sitemaps', 'django.contrib.humanize', 'posts', 'sidebars', 'general', 'categories', 'home', 'authors', 'taggit', 'cachalot', 'widgets', 'code_samples', 'hyper_links', 'polls', 'applications', 'videos', 'quotations', 'languages', 'people', 'arbitrary_htmls.apps.ArbitraryHtmlsConfig', 'tweets', 'vk_posts', 'facebook_posts', 'instagram_posts', 'email_subscriptions', 'social_share', 'assessments', 'django_bootstrap_breadcrumbs', 'promo', 'commonstuff', 'push', 'feeds'] Installed Middleware: ['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'] Traceback (most recent call last): File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/michael/PycharmProjects/pcask/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = … -
How to fetch data from Django REST Framework?
I just finished making my own basic REST Web Service by watching tutorials from youtube but the problem is all the Django REST Framework tutorials that I've seen only focuses on how to create REST API and I've never seen anyone explain how to integrate with it. So now I just want to ask how I can fetch the data from it? I mean I can Login or Get the data or even insert a data using Postman. But how can I do it using a Django Website? For example, if I make another Django Website and I want to use the REST API that I made. How can I do it? If possible I also want to Register/Login using the REST Web Service that I created. Note: I never tried any codes yet since I absolutely have no idea how to do it. -
How to resize width of html table so the last is bigger the the first two
I am new in Django,HTML and CSS and in stackoverflow and need your help. I have a table: <div class="grade_book"><table class="table"> <tr><th>Year</th><th>Grade</th><th>Category</th></tr> {% for year, grade, category in results %} <tr><td>{{year}}</td><td>{{grade}}</td><td>{{category}}</td></tr> {% endfor %} </table></div> I want to make the fisrt two columns width 100px and the third-the last one 250px. This is what i tried in CSS but it only makes the fisrt column 100 px. .grade_book table td {text-align: left;font-size: 14px;} .grade_book .table{ table-layout:fixed; font-size: 16px; width: 100%; margin-bottom: 100px; border-collapse: collapse;} .grade_book th { width: 90px;} .grade_book th+th { width: auto;} I really need your help i ma novice in CSS at all . Tried to findsimilar questions but i cannot get the result i want -
Django reset password failed, Email address is not verified
I want to use Amazon's Simple Email Service to send emails. I verified my domain as well as the email address I want to send from. I'm not in sandbox mode. I'm able to receive email when I sign up but when I try to reset the password I get SMTPDataError with exception (554, b'Message rejected: Email address is not verified. The following identities failed the check in region AP-SOUTH-1: webmaster@localhost') How can this issue be resolved? -
How do I change the rendering properties of a django choice field?
The below code is rendering 'US' or 'CA' to the template according to a user's response. How do I make it render the corresponding 'United States' or 'Canada' value instead two character code? From: models.py CANADA = 'CA' UNITED_STATES = 'US' COUNTRY_CHOICES = [ (CANADA, 'Canada'), (UNITED_STATES, 'United States'), ] address_country = models.CharField( max_length=2, choices=COUNTRY_CHOICES, default=UNITED_STATES, null=True, ) From: forms.py class AddressForm(forms.ModelForm): class Meta: model = Address fields = ['address_country',] labels = {'address_country': 'Country',} Template Country: {{address.address_country}} -
add Django leaflet location picker on DRF creation form
I'm using leaflet in my admin page easily by this code: from django.contrib import admin from leaflet.admin import LeafletGeoAdmin from location.models import Location admin.site.register(Location, LeafletGeoAdmin) and I have location picker in my admin page like this: I need this form in my DRF form. How to change the default template and add leaflet to the location field? Here are some of my codes: models.py from django.contrib.gis.db import models from account.models import Account class Location(models.Model): name = models.CharField(max_length=100) location = models.PointField() address = models.CharField(max_length=100, blank=True) created = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(Account, related_name='locations', default=1, on_delete=models.CASCADE) def save(self, *args, **kwargs): super(Location, self).save(*args, **kwargs) Seializer.py from rest_framework import serializers from rest_framework_gis.serializers import GeoFeatureModelSerializer from location.models import Location class LocationSerializer(GeoFeatureModelSerializer): class Meta: model = Location geo_field = 'location' auto_bbox = True fields = ['url', 'id', 'name', 'location', 'address', 'created', 'owner'] owner = serializers.ReadOnlyField(source='owner.username') views.py class LocationViewSet(viewsets.ModelViewSet): queryset = Location.objects.all() serializer_class = LocationSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly] bbox_filter_field = 'location' bbox_filter_include_overlapping = True filter_backends = [filters.SearchFilter, filters.OrderingFilter, InBBoxFilter, TMSTileFilter, DistanceToPointFilter] pagination_class = GeoJsonPagination search_fields = ['=name', 'owner'] ordering_fields = ['name', 'owner'] ordering = ['created'] def perform_create(self, serializer): serializer.save(owner=self.request.user) -
how to Django and MongoDB atlas
I m using Django and MongoDB as database.I m new to MongoDB. I m using MongoDB atlas to store data. Question:How to connect Django with MongoDB using Mongoengine. What I have Done so far: created account in Mongodb atlas. Installed mongoengine. -
Domain name replaced by upstream name in Nginx/uWSGI/Django stack
I moved an old Django-based website from an old and insecure server. Because of software dependencies, it is not possible to update the Django version from 1.x. Everything worked fine on the old server, but after moving to a new server the domain name gets replaced with the proxy_pass upstream name (keepalive) from Nginx whenever the site makes an HttpResponseRedirect(reverse(...)), so https://example/somewhere/ becomes https://keepalive/somewhere/. When this happens, the access is not recorded by the uWSGI server, but I can then change the URL in the browser, and that works. The Nginx site config looks like this: upstream keepalive { server 127.0.0.1:9000; keepalive 64; } server { listen 80; listen 443 ssl; server_name www.example.com example.com; ssl_certificate /var/www/example.com/config/server.cert; ssl_certificate_key /var/www/example.com/config/server.key; location /static/ { alias /var/www/example.com/example/static/static_root/; } location / { proxy_pass http://keepalive; proxy_set_header Connection ""; proxy_http_version 1.1; } access_log /var/log/nginx/example_access.log; error_log /var/log/nginx/example_error.log info; } -
User models registered to Django Admin
I'm a beginner in Django. I'm trying to make data user-specific in the Django admin panel. For example, I have a model registered with admin called courses. I have two users user A and User B. When I create a course with User A, User B must not see that. How can I achieve that with Django, is it something with sessions? If there are any keywords to search in google relevant to this please mention Thanks all, -
Redirect django 3.0 with parameters
i'm trying to redirect my views to another where is required the id parameter. This is my situation.. views.py enter image description here template enter image description here url.py enter image description here result : enter image description here thanks for help! -
How to find element ID based on container
I have a Django project where, on the homepage, I am generating rows on the click of a button. By default, row0 exists. When the button is clicked, a 'row1' is created, and when clicked again, 'row2' is created, and so on... In each row exists the same items: a search bar, a button, and a number input. Their IDs are created based on a counter. so the button creates a div with the ID 'row1' then in that row goes 'search1' 'button1' and 'number_input1' When the button is clicked, it takes the value input into the 'search0' element, and finds a value corresponding to that input... The problem is, I am finding the value by referencing the search bar with the id 'search0' although someone may be using row3... SO I am trying to determine how to find the search bar in the same row as the button being clicked. Example: If I click 'button3' (the button in the third row), then how can I reference 'search3'(the search bar in row3) without using it's ID. The trick is, this cannot be a static string because the rows are created dynamically, thus all buttons share the same function. Is there …