Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django & Geopy : calcul distance btwn fixed position (post) and moving position (user.userprofile) position
I am looking for how to define a distance between two points. The first one is related to the post itself and does not change. It indicates the position of the post. The second would be linked to the user's position. The problem is that nothing is displayed. Do you have an idea? Thanks a lot for your help, {% if user.is_authenticated %}{% if user.userprofile.longitude %} {{ post.distance_post }}km {% else %}{% endif %} {% endif %} post/models.py class Cuisine(models.Model): ... latitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, default='0') longitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, default='0') def distance_post(self, request): post_situation = (self.longitude, self.latitude) user_situation = (self.request.user.userprofile.longitude, self.request.user.userprofile.latitude) return geodesic(post_situation, user_situation).km user/models.py class UserProfile(models.Model): ... latitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, default='0') longitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, default='0') -
Deploy Django in intranet / Django production tipps
I have some experience with tinkering around with Django to make things simply work but I lack experience in deployments. I am able to access my service in the LAN, however I am not sure if this is a good and secure way of doing it. Is Django suitable for small intranet applications? How can i prevent access from outside of the intranet? What are the risks running a standard Django project in a LAN by calling runserver 0.0.0.0 8000 on a windows machine? Are there options for SSL in LAN? Are there other problems or tipps to consider? -
Django test throwing an error on response status code 404
I'm following along with a lecture on django testing and this is one of the tests: def test_invalid_flight_page(self): max_id = Flight.objects.all().aggregate(Max("id"))["id__max"] c = Client() response = c.get(f"/flights/{max_id + 1}") self.assertEqual(response.status_code, 404) When I run manage.py tests it throws an error on this test, essentially saying there is no matching flight: Creating test database for alias 'default'... System check identified no issues (0 silenced). .......E.. ====================================================================== ERROR: test_invalid_flight_page (flights.tests.FlightTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\sarah\Desktop\airline\flights\tests.py", line 68, in test_invalid_flight_page response = c.get(f"/flights/{max_id + 1}") File "C:\Python\Python385\lib\site-packages\django\test\client.py", line 732, in get response = super().get(path, data=data, secure=secure, **extra) File "C:\Python\Python385\lib\site-packages\django\test\client.py", line 393, in get return self.generic('GET', path, secure=secure, **{ File "C:\Python\Python385\lib\site-packages\django\test\client.py", line 470, in generic return self.request(**r) File "C:\Python\Python385\lib\site-packages\django\test\client.py", line 709, in request self.check_exception(response) File "C:\Python\Python385\lib\site-packages\django\test\client.py", line 571, in check_exception raise exc_value File "C:\Python\Python385\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Python\Python385\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\sarah\Desktop\airline\flights\views.py", line 21, in flight flight = Flight.objects.get(pk=flight_id) File "C:\Python\Python385\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Python\Python385\lib\site-packages\django\db\models\query.py", line 429, in get raise self.model.DoesNotExist( flights.models.Flight.DoesNotExist: Flight matching query does not exist. ---------------------------------------------------------------------- Ran 10 tests in 0.120s FAILED (errors=1) Destroying test database for alias 'default'... But … -
Django: Filtered Queryset only displaying stale data
I am new to python/django and have been creating a web application that filters data displayed based on group. Everything works perfectly from a create, edit and update side if I am logged in as a user with 'admin' as their group however if I login to any of the other groups it fails to display recently inserted data. The below code filters my "tasks" page based on what group is assigned to the user and displays the correct data. @login_required(login_url='login') @allowed_users(allowed_roles=['admin', 'Systems', 'Energy', 'Support', 'Environmental', 'Security', 'Safety', 'Projects', 'MRO']) def tasks(request): tasks = Task.objects.all().order_by('task', '-status', '-submission_date').distinct('task') group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group == 'Systems': tasks = Task.objects.filter(team__name__contains = 'Systems').order_by('task', '-status', '-submission_date').distinct('task') if group == 'Energy': tasks = Task.objects.filter(team__name__contains = 'Energy').order_by('task', '-status', '-submission_date').distinct('task') if group == 'Support': tasks = Task.objects.filter(team__name__contains = 'Support').order_by('task', '-status', '-submission_date').distinct('task') if group == 'Environmental': tasks = Task.objects.filter(team__name__contains = 'Environmental').order_by('task', '-status', '-submission_date').distinct('task') if group == 'Security': tasks = Task.objects.filter(team__name__contains = 'Security').order_by('task', '-status', '-submission_date').distinct('task') if group == 'Safety': tasks = Task.objects.filter(team__name__contains = 'Safety').order_by('task', '-status', '-submission_date').distinct('task') if group == 'Projects': tasks = Task.objects.filter(team__name__contains = 'Projects').order_by('task', '-status', '-submission_date').distinct('task') if group == 'MRO': tasks = Task.objects.filter(team__name__contains = 'MRO').order_by('task', '-status', '-submission_date').distinct('task') myFilter = TaskFilter(request.GET, queryset=tasks) tasks = myFilter.qs … -
Not finding static files Django Project in Apache
I read many questions about this, but still no able to solve it. i would appreciate any help. I am following the great tutorial of Corey Schafer https://www.youtube.com/watch?v=Sa_kQheCnds to deploy my django app in Linode. But I can't serve the static files. I already did manage.py collectstatic and here is my configuration: Settings.py /etc/apache2/sites-available/komposair.conf I copy and paste the lines of the tutorial (changed neccessary lines) My folder configuration Permissions I also changed the owner and permission (www-data) as explain in the tutorial and they seem fine. Still when I load my site in the console I get (refering to the static files): ******/:1 Failed to load resource: the server responded with a status of 404 (Not Found) Templates In my templates this is how I serve the static files (they worked fine in development) {% load static %} <!DOCTYPE html> <html lang="en"> <head> <!-- Add font awesome --> <script src="https://kit.fontawesome.com/37e8b20514.js" crossorigin="anonymous"></script> <!-- Custom styles and js for this template --> <link href="{% static 'melody/simple-sidebar.css' %}/" rel="stylesheet"> <script src="{% static 'melody/utils.js' %}/"></script> My urls Apache Error Log I found this line... AH01276 Cannot serve directory /home/juancopi81/komposair/static/: No matching DirectoryIndex (index.php...) found, and server-generated directory index forbidden by Options directive -
Form Post malfunction on Django login
I am trying to implement a login section on the landing page of a Django login but it keeps sending the data to the wrong view and making it appear in the url. In http://127.0.0.1:8000/ I have a pop up with this form <form action="login" method="POST"> {% csrf_token %} <input type="text" name="username" placeholder="Username"> <input type="password" name="password" placeholder="Password"> <input type="submit" value="Login"> </form> in urls.py i have path('', views.index, name='index'), path('register/', views.register, name='register'), path('login/', views.loginPage, name='login'), path('news/', views.news, name='news'), path('profile/', views.profile, name='profile'), path('friends/', views.friends, name='friends') etc and the view for log in it def loginPage(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) messages.info(request, 'Servus'+ username) return redirect('profile') else: messages.info(request, 'Username or Password is incorrect!') So ideally it should log in the user and then send it over (create a GET request) to the profile view. However it does not do that. It opens renders the friends view and creates a url that looks like this: http://127.0.0.1:8000/friends/?csrfmiddlewaretoken=roLEhPRiXf6QeX1rhsiWQ0D67gSfc4PCxvyc7YyxnEIBRfV3bOUzPbyFJUG026ys&username=C*****&password=H****** (I added **** to hide the username and password) However I am able log the user in if I create a separate url for the login and change the form action … -
Using Token Authentication in django, but i need to get user session length?
I am using a otp based user login in DRF and generating a Token for user signup and otp is matched , now i want to calculate the session length of each user on the platform , how to do this in DRF. -
Is it safe to store Auth Tokens directly in Redux?
I am currently building a seller dashboard for a local ecommerce platform and using Django for my backend and React for my frontend. I have Django Rest Framework serving my backend API to the frontend so my question is, What is the safest way of storing the token served from Django Rest Framework in Redux so that I can use it to talk to the backend. Is it a security risk by storing the token as a normal variable in the current Redux state? Never worked with Token auth before so curious to know if there is any security risk with how I would go about building it. -
How to add another field in HTLM forms in django like admin TabularInline
In django admin after added TabularInline the admin page shows "Add another " button in a specific model's add form, When user click that it will add another field and input box to the HTML form I need that in normal template how to do that Thanks Advance, Vignesh Karthik -
How do I save FileField using model's pk in Django
I created an upload function that saves an uploaded file using the pk or id. But I get a None as a folder in the instance.id. I followed the instruction on the post and I discovered that if you are using the id, you need to make sure the model instance was saved before you upload the file. Otherwise, the id hasn’t been set at that point and can’t be used. How can get the id instead of None..? I want to save the uploaded file to "media/id/uploaded_file upload_to function def upload_to(instance, filename): print('ID', instance.pk) return os.path.join(str(instance.id), filename) My model.py class MyVideo(models.Model): videofile= models.FileField(upload_to=upload_to) name= models.CharField(max_length=500) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name + ": " + str(self.videofile) -
Serializer all models with one serializer
I'm new in django and during my studies i came across the issue of a unique serialization. Normally, I would create one serializer for each model created, but i want to create just one serializer for all models. In a dynamic way. Example: models.py class Group(Base): __tablename__ = 'groups' id = sa.Column(sa.Integer(), primary_key=True, autoincrement=True) name = sa.Column(sa.String()) class User(Base): __tablename__ = 'users' id = sa.Column(sa.Integer(), primary_key=True, autoincrement=True) name = sa.Column(sa.String()) fullname = sa.Column(sa.String()) password = sa.Column(sa.String()) _group_id = sa.Column('group_id', sa.Integer(), sa.ForeignKey('groups.id')) group = sa.orm.relationship(Group, backref='users') class Address(Base): __tablename__ = 'addresses' id = sa.Column(sa.Integer(), primary_key=True, autoincrement=True) email_address = sa.Column(sa.String(), nullable=False) _user_id = sa.Column(sa.Integer(), sa.ForeignKey('users.id')) user = sa.orm.relationship(User, backref='addresses') I try to do something like this: class GeneralSerializer(serializers.ModelSerializer): class Meta: model = None session = session fields = '__all__' But I'm getting a NoneType as an answer: sqlalchemy.exc.NoInspectionAvailable: No inspection system is available for object of type <class 'NoneType'> Which makes sense, considering the skeleton of the serializer. I know this question was asked before, but I found no solution in the previous topic and nowhere else. I will probably have to work with the serializer init, but I still have no idea how to do it. I don't want a ready … -
Correct way of saving objects with URLField
I have a model class KeyWord class KeyWord(models.Model): keyword = models.CharField(verbose_name="Topic",max_length=50) link = models.URLField(verbose_name = "Next Best Action", max_length=500,null=True) def __str__(self): return self.keyword If i create an object like this: KeyWord.objects.create(keyword="hello",link="world") Ideally an error be raised because i am assigning normal text to link field which is a URLField but object created successfully? Which field should i use or what should i do so that objects with valid links are saved? -
How can query a collection in mongodb using django and djongo
I have a django application with mongodb as a backend database and djongo as a connector. I created a collection in the database using mongodb compass and I want to query the data in that collection. Is it possible or I need to have the data in a django model -
Saving data to elasticsearch with django
How can I save nested-json data to Elasticsearch with Django? I want to take data from Twitter, enrich it and save it to elasticsearch but jsonfield etc. not accepting. charfield or another saved data as string-not dict -
Is there any way I can pass a filtered query set into Django's pagination?
view.py def quiz(request): question_topic = request.POST.getlist("topic_checkbox") # Retrieves list of topics selected by user question_list = Quiz.objects.filter(Topic_name__in = question_topic) #filters out questions by topics paginator = Paginator(question_list,1) # when i pass all the objects rather than the filtered query set it seems to work but when i paginate with the filtered queryset only the first page loads page = request.GET.get('page') try: question_list = paginator.page(page) except PageNotAnInteger: question_list = paginator.page(1) except EmptyPage: question_list = paginator.page(paginator.num_pages) return render(request,"Quiz/quiz_home.html",{"question_list":question_list}) quiz_home.html {% block content %} {% for q in question_list %} # loops through the filtered queryset {% if question_list.has_next %} <h3>Question {{q.id}}</h3> <form method="POST" action="?page={{ question_list.next_page_number }}">{% csrf_token %} # The form should enable me to gather the users input whilst simultaneoulsy going to the next question in the for loop. But when question sumbitted the next page is blank showing no contents {% if q.picture %} <img src="/media/{{q.picture}}"> <br> {% endif %} {{q.id}}.) </label><label id="question_text">{{q.question}}</label><br> <input type="hidden" id= "q_id" name="q_id" value="{{q.id}}"> <input type="hidden" id= "topic" name="topic" value="{{q.topic}}"> <input type="radio" id="opt1" name="options" value="{{q.option1}}" required>{{ q.option1 }}<br> <input type="radio" id="opt2" name="options" value="{{q.option2}}" required>{{ q.option2 }}<br> <input type="radio" id="opt3" name="options" value="{{q.option3}}" required>{{ q.option3 }}<br> <hr> <input type="submit" id="mybtn" value="Submit"> #once clicked it should paginate to … -
Pretty print django.db.models.JSONField in Django admin?
Django >= 3.1 supports a new JSONField model field. I am using one like this: from django.db import models class Example(models.Model): foobar = models.JSONField() I've also included this model in Django's admin section. However, the field is just a simple textarea with the JSON included, not pretty printed. How can I make sure the JSON displayed in Django's admin section is pretty printed, with indentation, like this: { "example": { "a": 1, "b": 2 } } -
ModuleNotFoundError: No module named 'cart.context_processors'
I am working on the django project by following the book. I am using Django version : 3.1.2.I added 'cart' app to the project. But when I worked with context_processor , I get the error.Can someone help me? I'm having this error: error screenshot This is "settings.py" # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'shop.apps.ShopConfig', 'cart.apps.CartConfig', ] ROOT_URLCONF = 'myshop.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'cart.context_processors.cart', ], }, }, ] WSGI_APPLICATION = 'myshop.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } CART_SESSION_ID = 'cart' STATIC_URL = '/static/' -
Django TypeError: 'Library' object is not callable
I'm upgrading code to the latest version of Django Version: 3.1.2 from django.template import Variable, Library register = Library() def striplinebreaks(value, arg): """ Removes all values of arg from the given string. """ safe = isinstance(value, SafeData) value = value.replace('\n', u'').replace('\r', u'').replace('\t', u'') if safe and arg != ';': return mark_safe(value) return value register('striplinebreaks') getting this error File "/home/sam/code/kpsga/lamusoftware/generic/templatetags/striplinebreaks.py", line 18, in <module> register(striplinebreaks) TypeError: 'Library' object is not callable -
why is django 'objects.filter' giving empty variable?
Please ignore the question cause i am newbie. :) my django views.py -- def search(request): if request.method == 'POST': try: query = request.POST["query"] try: query2 = User.objects.get(username=query) except: query2 = None if query2 == None: results = info.objects.filter(name=query) else: results = info.objects.filter(user=query2, name=query) return render(request, "search.html", {"results": results}) # https://docs.djangoproject.com/en/dev/topics/db/queries/# #spanning-multi-valued-relationships except: messages.info(request, "User not found") return redirect(home) else: pass my html -- {{results}} {% for result in results %} <a href="profile_seen?profile_seen={{result.user}}-1"> <div style="border: 0.7px solid gray;" class="row card"> <div style="display: flex;align-items: center; justify-content: center;"> <img style="width: 107px; margin: 10px 2%;" class="img-fluid" src="https://facyfun-bucket.s3.ap-south-1.amazonaws.com/{{result.profile_pic}}" alt="error"> <ul style="padding: 11px 12%;" class="list-group list-group-flush"> <li style="font-size: 32px;" class="list-group-item p-0">{{result.user}}</li> <li style="font-size: 19px;" class="list-group-item p-0">{{result.name}}</li> <li style="font-size: 17px;" class="list-group-item p-0">age {{result.age}}y</li> </ul> </div> </div> </a> {% endfor %} Error -- It always sends empty variable(results). But admin shows that it has value. Thanks Mam/Sir in Advance. -
Is updating a postgres database from an unsupported version important?
So far, I see only two reasons that make me consider an update from Postgres 9.4 (which is already an unsupported version). I want to use Django 3.1 for the development of a new web and this new version of Django does not support Postgres 9.4 anymore. I would have a new functionality and maybe an improved performance. Are there other, maybe more important reasons why to update? Should I care that it is an unsupported verion? And if yes, is it worth to update all the way to the newest stable version? -
Using curl with @login_required
I have a function: def foo(request): qs = Example.objects.all() for query in qs: query.param += 10 query.save(update_fields=['param']) return redirect('main:index') urlpatterns = path('foo/', foo) When i add @login_required the function stops executing with curl. I tried using .netrc, -u, --digest, but it still doesn't work. * Trying 127.0.0.1:8000... * TCP_NODELAY set * Connected to localhost (127.0.0.1) port 8000 (#0) * Server auth using Basic with user 'admin' > GET /foo/ HTTP/1.1 > Host: localhost:8000 > Authorization: Basic YwrtaW76Ttd0d4E7BWo= > User-Agent: curl/7.68.0 > Accept: */* > * Mark bundle as not supporting multiuse < HTTP/1.1 302 Found < Date: Mon, 26 Oct 2020 20:24:37 GMT < Server: WSGIServer/0.2 CPython/3.8.5 < Content-Type: text/html; charset=utf-8 < Location: /users/login/?next=/foo/ < X-Frame-Options: DENY < Content-Length: 0 < Vary: Cookie < X-Content-Type-Options: nosniff < Referrer-Policy: same-origin < * Connection #0 to host localhost left intact -
How to run django migrations with one command
I have an issue with Django migration. I have more than one database in my project. And I want to do the migration for all of them. I wrote my own migrations and if I run the commands below, everything works fine. python manage.py migrate app-name first_migration python manage.py migrate --datatbase=db_1 app-name first_migration python manage.py migrate --datatbase=db_2 app-name first_migration python manage.py migrate app-name second_migration python manage.py migrate --datatbase=db_1 app-name second_migration python manage.py migrate --datatbase=db_2 app-name second_migration python manage.py migrate app-name third_migration python manage.py migrate --datatbase=db_1 app-name third_migration python manage.py migrate --datatbase=db_2 app-name third_migration But I want to automate it, to run only: python manage.py migrate Unfortunately, when I do it I have the below error for migration3 django.db.utils.operationalerror no such column: column_name But column_name was added in migration2 Have anybody any idea, how can I resolve this issue and run all migration with one command? -
Django/Heroku AJAX Request Doesn't Seem To Execute
I am needing to save the contents of a javascript variable in the main page of my site (index.html), to the database that my heroku/django app is connected to. I found a related post here but my AJAX request to send a variable from JavaScript to then access in python is not running. Javascript/HTML and AJAX in index.html: <button type="button" id="send-my-url-to-django-button">Send URL to Django View</button> <script type="text/javascript"> $(document).ready(function() { var url = data.result.docs[i].source.enriched.url.url; alert("ok"); $("#send-my-url-to-django-button").click(function() { $.ajax({ url: "/process_url_from_client", type: "POST", dataType: "json", data: { url: url, csrfmiddlewaretoken: '{{ csrf_token }}' }, success : function(json) { alert("Successfully sent the URL to Django"); }, error : function(xhr,errmsg,err) { alert("Could not send URL to Django. Error: " + xhr.status + ": " + xhr.responseText); } return false; }); }); }); </script> relevant lines from urls.py url(r'^process_url_from_client/$', hello.views.process_url_from_client, name='process_url_from_client'), relevant lines from views.py def process_url_from_client(request): url = request.POST.get('url') save = SaveFile(data=str(url)); save.save(); This is supposed to send the URL from index.html to then be accessed in views.py and saved to the database. However clicking the button does not seem to execute the AJAX script at all. I don't get a success or error message. Any ideas why this isn't working? Any help would … -
topics = Topic.objects.filter(owner=request.user).order_by('date_added') Not working
I'm a beginner in Django and I'm using a book called Python Crash Course to guide me. I am currently doing the app development project and I'm running into some errors. Apparently, the error is caused by this line: topics = Topic.objects.filter(owner=request.user).order_by('date_added'). Here is my full code for views.py: from django.shortcuts import render from django.http import HttpResponseRedirect, Http404 from django.http import HttpResponseRedirect from django.urls import reverse from django.contrib.auth.decorators import login_required from .models import Topic, Entry from .forms import TopicForm, EntryForm def index(request): return render(request, 'learning_logs/index.html') @login_required def topics(request): topics = Topic.objects.filter(owner=request.user).order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) @login_required def topic(request, topic_id): topic = Topic.objects.get(id=topic_id) if topic.owner != request.user: raise Http404 entries = topic.entry_set.order_by('-date_added') context = {'topic': topic, 'entries': entries} return render(request, 'learning_logs/topic.html', context) @login_required def new_topic(request): if request.method != 'POST': form = TopicForm() else: form = TopicForm(data=request.POST) if form.is_valid(): new_topic = form.save(commit=False) new_topic.owner = request.user new_topic.save() form.save() return HttpResponseRedirect(reverse('learning_logs:topics')) context = {'form': form} return render(request, 'learning_logs/new_topic.html', context) @login_required def new_entry(request, topic_id): topic = Topic.objects.get(id=topic_id) if request.method != 'POST': form = EntryForm() else: form = EntryForm(data=request.POST) if form.is_valid(): new_entry = form.save(commit=False) new_entry.topic = topic new_entry.save() return HttpResponseRedirect(reverse('learning_logs:topic', args=[topic_id])) context = {'topic': topic, 'form': form} return render(request, 'learning_logs/new_entry.html', context) @login_required … -
Reading Froms.py code from Model data in django
I have a some class in forms.py and I want reading code by user entry in specific model for example This code need read from model user entry class SearchForm(BSQuickSearchForm): def layout(self): self.helper.layout = Layout( 'q_quick_search_kw', StrictButton('Search', type="submit", css_class='btn-sm btn-default'), StrictButton('Export', type="submit", name="export", css_class='btn-sm btn-default'), )