Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to populate a modelfield via django signals with post_save?
after creating a modelobject i would like to use a post_save signal to populate another modelfield in the same object with the ID and other values But the real question here is, how do i access the field from the instance? nothing worked Example: User creates an object -> ID of the object is 93 -> i would like to add #00093 into another field in the same object models.py class Ticket(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) designation = models.CharField(max_length=255, blank=True, null=True) summary = models.CharField(max_length=255) my signals.py @receiver(post_save, sender=Ticket) def ticket_designation(sender, instance, **kwargs): instance.designation = "#" + "000" + str(instance.id) print("Ticket" + instance.designation + " was created.") -
Can I retrieve the headers of a request or its content in VueJS?
I need to redirect my django app to my VueJS app, and I would like to forward information from one to other. I can not see how I retrieve the headers request or the content request from an input request. -
I cannot found modules in Django
I'm trying to connect my Django with my MongoDB. So, first of all, I install this: pip install djongo And all go fine, no errors. But If you see my models.py archive: It's like Django it's not finding and I can't import the models. I tried to install again Django, but it says to me that it's already installed. I think I'm installing this in another path or something like that, but I don't know how to solve this. My Django archive its in C:\PROYECTOS\PageSpeed_Insights__Selenium-Python\miweb -
django-elasticsearch-dsl-drf: TypeError: search() got an unexpected keyword argument 'doc_type'
I am creating an django API with Elastic search, using below libraries: django-rest-framework django-elasticsearch-dsl django-elasticsearch-dsl-drf When api is called, django-elasticsearch-dsl-drf library throws error: search() got an unexpected keyword argument 'doc_type' Here is my code: serializers.py class TestSerializer(DocumentSerializer): class Meta(object): document = TestDocument fields = ("id", "name") api.py class TestDocumentViewSet(DocumentViewSet): document = TestDocument serializer_class = TestSerializer lookup_field = 'id' filter_backends = [ CompoundSearchFilterBackend, ] multi_match_search_fields = ('id', 'name') filter_fields = { 'id': 'id', 'name': 'name', } ordering_fields = { 'id': 'id', 'name': 'name', } ordering = ('id', 'name') Can someone please help me out with this? -
djano complex postgre query parsing
Consider the following test models to query in django: class Detail(models.Model): drivers = models.ManyToManyField('Driver') weathers = models.ManyToManyField('Weather') ... class Trip(models.Model): detail = models.ForeignKey('Detail', on_delete=models.CASCADE) date = models.DateField(auto_now=False) routes = models.ManyToManyField('Route') ... For the model Trip the user in the frontend can submit an arbitrary nested query string on the id of the fields with parenthesis like querystring="(driver = [1] AND routes = [3]) OR ( driver = [2] AND weather = [1] )" I want to use djangos complex Q function to query this string in the backend, meaning I need to turn querystring into something like criterion = (Q(detail__drivers__id__in = ([1])) & ( Q(routes__id__in = ([3]))) | \ (Q(detail__driver__id__in = ([2])) & Q(detail__weather__id__in = ([1])) ) in order to be able to filter using self.queryset.filter(criterion) But how can I translate the string into the criterion while maintaining the parentheses structure? -
how to fix passing variable from view to html
i have a problem passing variable 'res' from view to index.html, it's return the last result in the html page view file: def index(request): posts = Layout.objects.all() urlpost = SiteUrls.objects.all()[:20] field_value = SiteUrls.objects.values_list('site_url', flat=True) for site_url in field_value: print(site_url) res = os.system("ping -n 1 " + site_url ) if res == 0: res = "connected" else: res = "not connected" context = { 'posts':posts, 'urlpost':urlpost, 'res': res } return render (request, 'posts/index.html', context) html file: <tbody> {% for SiteUrls in urlpost %} <tr> <td>{{SiteUrls.site_title}}</td> <td>{{SiteUrls.site_url}}</td> <td> {{res}} </td> <td><a style="margin-bottom:10px" class="waves-effect waves-light btn">open Site</a></td> </tr> {% endfor %} </tbody> </table> i would like to get back the specific result for each line -
How to extend my endpoint with /download/?
My code looks like this: # models.py class Recording(models.Model): title = . . . duration = . . . # views.py class RecordingViewSet(viewsets.ModelViewSet): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) serializer_class = RecordingSerializer . . . # urls.py router = routers.DefaultRouter() router.register(r'recordings', RecordingViewSet, base_name='recordings') How can I extend my endpoint to create a /recordings/X/ endpoint? (in my case X = download) -
Traefik equivalent of nginx X-Accel-Redirect header
I have plans to use cookiecutter-django to jump-start an app that serves large static files to authenticated users. Since the files may only be available to authenticated users, they have to be served via Django. But the files are too big to wrap in a Django file response. (Or appear to be. I get memory errors when I try.) I did this before with a project that I migrated to cookiecutter-django when they were using Caddy as a reverse proxy. The change at that point was simple. Caddy uses the same header as nginx, the X-Accel-Redirect header, to tell the proxy to serve an otherwise inaccessible file instead of forwarding the response. (There's a good description of the config required with nginx here; it's not very different with Caddy.) Now cookiecutter-django has ditched Caddy (for reasons I understand) and started using Traefik. But I have no idea how to accomplish the same thing with Traefik. It appears it may not be possible at all, since Traefik isn't actually a web server. How might I create a similar configuration with this new version of cookiecutter-django? -
Django, browser display filename instead of the picture
I am missing some element to display picture attatched with each post on a blog created with Django instead of picture file name. Many solutions to this kind of a problem were: <img src="{{Object.picture.url}}"/> On template I have tried: 1 <img src="{{ posts.title_picture.url }}"/> 2 <img src="{{title_picture.url}}"/> Which resulted respectively in displaying those on the browser: 1. pictureforpost1.png 2. img model: class Post(models.Model): title = models.CharField(max_length=255, blank=True, null=True) title_picture = models.FileField(blank=True,null=True) view: class IndexView(ListView): model = Post context_object_name = 'posts' Seems like Django is finding the file. It is just not displaying the picture. -
Object is not JSON serializable since sessions.backends has been changed
my site uses a 2 Factor auth mechanism through PGP public keys a user can set on his profile page. This was wronking pretty well but since i implemented a single-session policy i found here: How to prevent multiple login in Django <- My 2FA pages returns Object of type PGPMessage is not JSON serializable This behaviour become present as soon as i changed: SESSION_ENGINE = "django.contrib.sessions.backends.cache" to SESSION_ENGINE = "django.contrib.sessions.backends.db" at settings.py. So i guess I'm simply unable to handle the session right but why i'm able to get all needed data from the cache but not from the db as configured at settings.py still remains a secret to me. models.py class UserSession(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) session = models.OneToOneField(Session, on_delete=models.CASCADE) signals.py from django.contrib.auth import user_logged_in from django.contrib.sessions.models import Session from django.dispatch.dispatcher import receiver from .models import UserSession @receiver(user_logged_in) def remove_other_sessions(sender, user, request, **kwargs): # remove other sessions Session.objects.filter(usersession__user=user).delete() # save current session request.session.save() # create a link from the user to the current session (for later removal) UserSession.objects.get_or_create( user=user, session=Session.objects.get(pk=request.session.session_key) ) views.py def 2fa(request): if request.method == 'POST': form = Login2faForm(request.POST) if form.is_valid(): if request.POST['token'] == request.session['token']: user = User.objects.get(id=request.session['userID']) hybridlogin(request, user) return redirect(reverse('home')) else: encrypted_token_message = request.session['encrypted_token'] … -
Develop an application on 2 different machine
I would like to develop a web application (Django 1.11, python 2.7) on 2 different machines: the morning developping on a computer and the evening on another computer. currently I copy the entire folder from one machine to another Is there another way? -
Django Project, centering forms on html template
I am trying to simply center a form that has been rendered on a Django html template. It is a bootstrap component (form), and I have tried putting the 'center' html tags in various places but with no success. I have tried putting the center tags outside the form, outside the Django templating language blocks, and in the base template, outside the div. Could someone please advise on a) how to solve the problem b) best practices for applying formatting, as in this case. page.html (that extends base2.html) {% extends "socialmedia/base2.html" %} {% load static %} {% block title %}Welcome to the test page{% endblock %} {% block heading %}Welcome,,,,{% endblock %} <center> {% block content1 %} <class="form-group row"> <label for="inputEmail3" class="col-sm-2 col-form-label">Email</label> <div class="col-sm-10"> <input type="email" class="form-control" id="inputEmail3" placeholder="Email"> </div> </div> <div class="form-group row"> <label for="inputPassword3" class="col-sm-2 col-form-label">Password</label> <div class="col-sm-10"> <input type="password" class="form-control" id="inputPassword3" placeholder="Password"> </div> </div> <fieldset class="form-group"> <div class="row"> <legend class="col-form-label col-sm-2 pt-0">Radios</legend> <div class="col-sm-10"> <div class="form-check"> <input class="form-check-input" type="radio" name="gridRadios" id="gridRadios1" value="option1" checked> <label class="form-check-label" for="gridRadios1"> First radio </label> </div> <div class="form-check"> <input class="form-check-input" type="radio" name="gridRadios" id="gridRadios2" value="option2"> <label class="form-check-label" for="gridRadios2"> Second radio </label> </div> <div class="form-check disabled"> <input class="form-check-input" type="radio" name="gridRadios" id="gridRadios3" value="option3" disabled> <label … -
How to make hidden field in django admin create form?
I want to set Hidden field in admin side form. I have product form. in this form i want to set discount price hidden. i use exclude function but its remove whole field. i want to hidden this field in form. -
Django: What is the difference between UserCreationForm and Abstractbaseuser / BaseUserManager when making a login/register page?
Whilst I was trying to search for methods to create a registration and login, I stumbled upon two distinctively different methods that, I think, produce the same result. So from what I understand through my research: you can create a customized user registration page by adding onto the UserCreationForm method so that you can include more fields in the model. HOWEVER, I realize that with the long tedious method of AbstractBaseUser and BaseUserManager, the end result is similar to the former in the sense that you end up with a customized user model / registration page. So I am unsure of the difference between these two different methods. I'm thinking that UserCreationForm does not allow you to create a superuser and staffuser but only allows you to create a normal user. Sorry if this question seems dumb because I just got started with Django and Python. -
how to drop an specific Django table which uses postgresql?
I want to delete a Django UserModel table and then recreate it. my db is postgresql on a docker container. -
I am learning django, when I use Pinax Likes, there is a 405 error
Django 2.2.1 When I use Pinax Likes(https://github.com/pinax/pinax-likes), there is a 405 error. The steps are as follows: pip3 install pinax-likes Added 'pinax.likes', to the project's settings.py file, then added: PINAX_LIKES_LIKABLE_MODELS = { "app.Post": {} } Added re_path(r'^likes/', include(('pinax.likes.urls', 'pinax_likes'), namespace='pinax_likes')), to the project's urls.py file, Download the files in the https://github.com/pinax/pinax-templates/tree/master/pinax/templates/templates/pinax/likes, put these html files in /home/www/venv/templates/pinax/likes/, Added {% load pinax_likes_tags %} {% likes_widget request.user post %} to the post.html file, python manage.py makemigrations app && python manage.py migrate && python manage.py runserver 0.0.0.0:8000 Open http://127.0.0.1:8000/post/13/, like icon appears, when clicked the icon(url: http://127.0.0.1:8000/like/14:13/), show the following: HTTP ERROR 405 What are the steps wrong? Thank you! -
Django ORM order by day from ISO time and score
HI in my database I have some data with created date and and some score associated with it.The created_date is of type DateTime. I am using django ORM. The data is like **col1 created_date score** xxx 2019-05-28T10:07:57.000Z 8 yye 2019-05-27T10:07:57.000Z 9 abc 2019-05-28T09:07:57.000Z 10 I want my date to be sorted by day then score in descending order ie abc 2019-05-28T09:07:57.000Z 10 xxx 2019-05-28T10:07:57.000Z 8 yye 2019-05-27T10:07:57.000Z 9 I am using SomeModel.objects.values_list(col , score, created_date ).filter(somefilter tcategory=cat).order_by( '-created_date__day', '-score') I am getting exception -- raise NotImplementedError('subclasses of BaseDatabaseOperations may require a datetime_extract_sql() method') NotImplementedError: subclasses of BaseDatabaseOperations may require a datetime_extract_sql() method Thanks -
Django going to external website with my variables in url
I have a model and i want to go to a external website with my variables in the url . For example: "www.example.com\ {% object.field %} .com My model class Avaria(models.Model): freguesia = models.ForeignKey(Freguesia, on_delete=models.CASCADE,verbose_name="Freguesia") rua = models.ForeignKey(Rua, on_delete=models.CASCADE,verbose_name="Rua") I'm changing my change_form_object_tools.html and add a extra li to do something like this: <li> <a href="https://example.com\{% obj.freguesia%}\{% obj.rua%}">{% trans "Example" %</a> </li> If i use the original.pk it is working but i want to use another field that is not the primary key -
How to setup timezone support in Django-admin for DateTimeField?
We have a Django model Contest: class Contest(models.Model): ... time_start = models.DateTimeField() Django settings.py has the following TZ settings: LANGUAGE_CODE = 'ru-ru' TIME_ZONE = 'Europe/Moscow' USE_I18N = True USE_L10N = True USE_TZ = True Server time is set to MSK+03 timezone: $ date Wed May 29 12:41:14 MSK 2019 What is expected Django stores UTC-datetime in database. When I open object for edit, django-admin converts UTC-datetime from database to my local computer timezone, which is already stored in my django session. And vice versa, when I save object with date, it's converted from my local computer TZ, entered in django admin, to UTC and stored in database. What I got Instead of converting received datetime to UTC, Django just corrects it with TIME_ZONE offset and saves to DB. It doesn't matter, which TZ is used on my local computed — US/RU/etc. It always subtracts -03 hours as 'Europe/Moscow' offset is +03, and saved the result to DB. When I change TZ on my local computer and re-login to django-admin, object datetime is not corrected to respect my current client TZ, but always stays the same despite I use different timezone. So, how it supposed to work? DB MariaDB> describe contest; … -
error code not available in axios response (react frontend) when 503 service maintenance
When maintenance mode of heroku turned on, it creates a 503 error in the frontend. The problem is there aren't any distinguishable property in the error response which only says Error: Network Error at createError (createError.js:17) at XMLHttpRequest.handleError (xhr.js:87) type of it still and object but there arent any items in it. This is a react-app run on a Django server and hosted on Heroku. axios.get('myAPI').then(res => { ... }) .catch(e => console.log(e) is there any way to distinguish 503 on the front-end? -
Django OAuth2 : Retrieve Access Token by passing client secret in Basic header
I want to retrieve an access token from my django server using an authorization code. It works when I provide the client_id and client_secret in the parameters of the request, but when I pass them using Basic Auth the server respond an error. I have a django server using django-oauth-toolkit to implement OAuth2 authentication. The Authorization Code flow works smoothly, but I want to implement it with Basic Auth to Authenticate the client. The client application has been added in django admin panel. Both server and client are mine, but for future compatibility with third party API I need the implement the Basic Authentication for client application when retrieving the access token. On client side, sending a request with client infos in parameters get me the access token but the passing the info in the HTTPBasicAuth give me an error. import base64 import json from urllib.parse import urlencode import requests MY_APP_CLIENT_ID = 'my_client_id' MY_APP_CLIENT_SECRET = 'my_client_secret' print('input authorization code:') oauth_code = input() headers = { 'Content-Type': "application/x-www-form-urlencoded", } encoded_payload = urlencode({ 'grant_type': 'authorization_code', 'code': oauth_code, 'redirect_uri': 'http://localhost/my_app/oauth2/redirect_uri', 'client_id': MY_APP_CLIENT_ID, 'client_secret': MY_APP_CLIENT_SECRET }) response = requests.post('http://localhost:8000/o/token/', data=encoded_payload, headers=headers) print(response.status_code) # 200 print(response.json()) # {'access_token': 'JEDsAwRh', 'expires_in': 36000, 'token_type': 'Bearer', 'scope': 'my_scope', … -
Using include tags inside of a foor loop
I'm following a tutorial that tells me write this code. But the problem is that Django seems to dislike the way I use the include Tag inside of a for Loop. {% extends 'base.html' %} {% block content %} {% for product in products %} {% inlcude 'products/snippets/card.html' %} <p>hey</p> {% endfor %} {% endblock content %} Here is the error TemplateSyntaxError at /products/ Invalid block tag on line 4: 'inlcude', expected 'empty' or 'endfor'. Did you forget to register or load this tag? -
Obtaining data from the GET form. Django
How can I get data from the form using the GET method? For example, I have this form: class LoansSearchForm(forms.Form): balance = forms.IntegerField(label='', required=False) In my view display in the form template this way: def search_results(request): form = LoansSearchForm(request.GET) cd = form.cleaned_data word = cd['balance'] context = {'form': form, 'test': word,} return render(request, 'search_results.html', context) But i still a error: 'LoansSearchForm' object has no attribute 'cleaned_data' When trying to get them this way: word = form['balance'] I receive a field with completed data. How to get the data from my the form correctly? Is my form written correctly? Should I use something like that? (sorry if my question is trivial, but I found very little information about GET forms) if request.method == 'GET': form = LoansSearchForm(request.GET) if form.is_valid(): print('Hello World') else: form = LoansSearchForm() -
passing decorator in django url gives 'tuple' object is not callable error
def UrlRequired(function): @wraps(function) def wrap(request, *args, **kwargs): if 'id' in request.session and 'url' not in request.session: request.session.delete() return HttpResponseRedirect('/home/') else: return function(request, *args, **kwargs) return wrap this is my custom decorator which i am passing through project level url so it would be accessed by all the functions who are extending the respective url but it is giving such error. TypeError at /home/ 'tuple' object is not callable url : url(r'home/',UrlRequired(include('app.urls',namespace='homee'))), -
How to use Django(2.2) REMOTE_USER data in request_negotiate_sspi api in python 3.7 to authenticate my TFS server?
I am using python to get data from TFS and want to use the REMOTE_USER data from Django to authenticate my TFS.