Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to handle highlighted text in django?
I'm new to web development. I would like to make a simple web-app to display 2 filled large text areas side by side. First one should allow getting the text highlighted by the user. The second should be automatically scrollable to specific position based on the highlighted text from the first text area. I’m using python and django for this. What kind of text area allows what I want to do? it would be great if you can direct me to some examples to help me with task? please feel free to recommend any other alternative approach -
Django - PostgreSQL options
I'm using Django 1.10 I couldn't find anywhere a full list of the options that can be used from Django settings to configure PostgreSql DB. I assume that part of the list can be found here - 33.1.2. Parameter Key Words But for example, it contains the option - options which as I understand allows many more options, but I didn't find proper documentation about how to use it. Example of using Django OPTIONS - DATABASES[DEFAULT]['OPTIONS'] = {'connect_timeout': float(os.getenv('DB_OPTIONS_TIMEOUT', 5))} -
Python request gets lost on DJango app deployed on IIS
I have deployed DJango app on IIS. It fetches tweets using tweepy. While i fetch historic tweets in between request gets lost and nothing gets logged and no exception is raised. I have attached code snippet. Note: When i run the same code in debug mode, everything works charm. This code gets status of each tweet by id. def get_tweet(id, api=None): status = [] try: logger.info('retrieve_tweet.get_tweet() invoked.') if api is None: logger.info('get_tweet api none found.') CONSUMER_KEY = config.TWITTER_CONSUMER_KEY CONSUMER_SECRET = config.TWITTER_CONSUMER_SECRET ACCESS_TOKEN = config.TWITTER_ACCESS_TOKEN ACCESS_TOKEN_SECRET = config.TWITTER_ACCESS_TOKEN_SECRET auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET) api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True, retry_count=2, retry_delay=5, retry_errors=[401], timeout=300000) status = api.get_status(id, tweet_mode='extended') logger.info('retrieve_tweet.get_tweet() end.') return status except Exception as ex: logger.error('Exception in retrieve_tweet.get_tweet(): %s', ex) return None Below code gets the parent tweet from the fetched conversation: child_status = get_tweet(id=id, api=api) logger.info('child_status: %s', child_status) if child_status: status.append(child_status._json) in_reply_to_status_id = child_status.in_reply_to_status_id while in_reply_to_status_id is not None: parent_status = get_tweet(id=child_status.in_reply_to_status_id, api=api) logger.info('parent status inside while: %s', parent_status) if parent_status: status.append(parent_status._json) in_reply_to_status_id = parent_status.in_reply_to_status_id if in_reply_to_status_id is None: logger.info('All the parent tweets are found.') else: child_status = parent_status else: in_reply_to_status_id = None if len(status) > 1: status = sorted(status, key=lambda x: x['id']) else: logger.info('no parent tweets found.') status = … -
Django; How to filter and make objects distinct
I'm creating a project using Django and I'm wondering how I can make objects distinct. Now I am creating message box part and what I want to do is show up user names who the user have been contacting. My current way is like this models.py class Message(models.Model): '''''' text = models.TextField() created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='myself') someone = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='someone') views.py def inbox(request): '''See messages history''' messages = Message.objects.filter(user=request.user).distinct('someone') notification = Message.objects.filter(someone=request.user).distinct('user') return render(request, 'campus_feed/inbox.html', {'messages': messages}) So what I want to do is list the users who is contacting me or I contacted and I don't want to show up the same name multiple times but I cannot come up with good way to filter them. Anyone who can give me tips? -
How to use Arangodb in Django database?
I am starting developing a website, I want to use Django and Arangodb, but Django's built-in databases backend does not support arango. django documentation refers to this in database section: You can use a database backend that doesn’t ship with Django by setting ENGINE to a fully-qualified path (i.e. mypackage.backends.whatever). but I could not find anything that bridges between Django and Arango. there is this repo in GitHub https://github.com/pablotcarreira/django-arangodb but this does not support new features of Django and Arango. I would like any thread to lead me to solve this problem. -
Django authentication issues in multi-language site
I'm learning Django 2 by making a bookstore project. The project itself based on the code from Django 2 by Example book (2nd edition). Currently Russian Localization is made using i18n and django-parler translatable models. The Problem №1. When I logged in under some user, (for example in English site version) everything that is related with users app (custom auth, registration, password changing) works fine on both localisations. But when I'm trying to log out (on English or Russian) - It works only on the current localisation. If I hit "Russian" on the language list of the navbar - I'm still logged in and I can perform all actions relatad to this user. So I click "Logout" again and now I'm logged out on both site versions. The same thing is happening with all users in my db. But, here is The Problem №2. When I logged out from the previous session from both site versions - logging again under the same user cause 403 Forbidden (CSRF token missing or incorrect.) Sorry for my bad English:) View full source code on GitHub users/views.py from django.contrib import messages from django.contrib.auth import authenticate, login, update_session_auth_hash from django.contrib.auth.decorators import login_required from django.contrib.auth.views import … -
Django - which CBV allows update & get multiple objects?
I have two models: class BHA_List(models.Model): well = models.ForeignKey(WellInfo, 'CASCADE', related_name='bha_list') bha_number = models.CharField(max_length=100) class BHA_overall(models.Model): bha_number = models.ForeignKey(BHA_List, 'CASCADE', related_name='bha_overall') drill_str_name = models.CharField(max_length=111) depth_in = models.CharField(max_length=111) And now consider the following example code using UpdateView: class BHA_UpdateView(UpdateView): model = BHA_overall pk_url_kwarg = 'pk_alt' form_class = BHA_overall_Form This code will query BHA_overall model instances using pk_url_kwarg = 'pk_alt'. However, I want pk_url_kwarg = 'pk_alt' to query instances of model = BHA_List, but its get_object() method to get instances of model = BHA_overall. Is there any way to trick Django to do this? The url pattern looks like this: re_path(r'^bha/(?P<pk_alt>[-\w]+)$', base_views.BHA_UpdateView.as_view(), name='bha') And the frontend looks like this: You can now edit [ BHA 2 ]: # url = .../bha/2 BHA Overall Information - Drill_str_name: [] Depth_in: [] ... Other Child Model - other_field: [] other_field: [] I need pk_url_kwarg = 'pk_alt' to query model = BHA_List and generate url, but I still need to return model = BHA_overall objects to display & allow users to edit data. What CBV should I use? Any example code that fits my purpose? -
Django choose version to upgrade
We're currently on django 1.9 and we want to upgrade to newer version of django. We don't know how to choose version to upgrade, since 1.11 is LTS and could be easier to upgrade and 2.0 is not LTS but later it will be easier to upgrade to 2.x LTS. Could you please give us some hints? Any help is appreciated. -
How to use one form in different pages?
Assume that we have one form like this: class SubscriberForm(forms.ModelForm): class Meta(){ model = Subscriber } fields = ('email', ) And our view is class AddSubscriber(CreateView): form_class = SubscriberForm model = Subscriber def form_valid(self, form): subscriber = form.save(commit=False) subscriber.save() return redirect('events_list') How can I use this form in many different pages? -
How can I add a link to download a file in a Django admin form?
So I want to put a button or link that downloads a file in an admin form. So, I want to create a file containing a string and allow the user to download the file when they click a button in the form. Any ideas? I am new to Django. Probably add html to the form? But how can I do that?. Remember I need to create the file on the fly. I need to create a file that contains a string of a model and provide a link to download it in an admin form. -
Ionic app authentication with Django back end server
I'm currently building an Ionic app consuming data from a Django back end server through Rest API. The problem I'm currently having is that some of the data passed back and forth between the app and the server are sensitive and specific to the user. So I would like to create some kind of authentication so that I can pass these information securely and my Django server can save and retrieve info from the correct user. How should I go about doing this? I'm quite new to Django so any advice would be appreciated. -
Django Models relation Problems
I am very new in django, Please help me out with this code. I want to make a relationship between student and course and functionality 1) Each student can select three courses 2) Each course can be opted by many students 3) Each student and course need not to be in the same department and school 4) Student cannot select courses from his department School_of_Physical_Scienes=('Physics','Chemistry','Mathematics') School_of_Earth_Sciences=('Environmental_Science','Geology','Forestry') class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=200) rollno= models.CharField(max_length=200) school = models.CharField(max_length=200) department = models.CharField(max_length=200) #student can select three courses from a pool of courses avalaible #one student 3 courses courseOption_1 =models.OneToOneField() courseOption_2 =models.OneToOneField() courseOption_3 =models.OneToOneField() #one course can be opted by many students class Course(models.Model): School = models.CharField(max_length=300) Department = models.CharField(max_length=300) courseName= models.CharField(max_length=300) courseCode= models.CharField(max_length=300) -
Heroku - deploying django react app
The project that I have created has django-rest-framework's API's running at port:8000 and the react app running at port:3000. Now, I have followed this to run react at port:8000 at '/'. Then, I have followed this post to deploy to heroku. And, this to set up my postrge sql. The rest-framework api's and django admin pages are working after deploying. So, the '/api/..' URLs and the '/admin/' URL are working. Going to base URL '/' is rendering nothing and giving this error message in the console. GET http://localhost:3000/static/js/bundle.js 0 () -
Django filtering on foreign key properties, difference between explicit and implicit foreign key property naming
Suppose I have two models - class A(models.Model): a_id=models.CharField(max_length=255,primary_key=True) a_name=models.CharField(max_length=255) class B(models.Model): a=models.ForeignKey(A) b_name=models.CharField(max_length=255) I want to filter B objects which belong to a particular a_id. I can either do this - B.objects.filter(a=a_id) or B.objects.filter(a__a_id=a_id) Is there any difference between the two, in terms of efficiency, speed or functionality? -
how to get reddit data using api calls
guys i want to create a web app function that gets data from other websites and post it in my website wall i have learned all the logic needed for this i want to get data of reddit using python requests request.get("reddit.com/api") some thing like this but the i dont understand the concept of authorization of a site for facebook/medium/reddit do we need to authorize for Retrieving data as well ,not for posting did a lot of research on medium facebook as well as reddit but that is of no use everything looks messy it would be help full for me if someone could share the exact process of getting data from other site any kind of help is appreciated -
How to use value from dictionary returned by QuerySet in Django
I wrote this query p_name = OrderLine.objects.filter(order_id=order).values('product_name') and it is returning the following results <QuerySet [{'product_name': 'doc 1 (1-1000)'}]> I want to use only doc 1 (1-1000) as a string. Is there a method for this. I read on some website to use .values() but is returning [{'product_name': 'doc 1 (1-1000)'}] -
django rest and jwt login user give me error: JWT only supports JSON objects as payloads
this is my login section to give a token to authenticated user . when i try to login it say : raise TypeError('Expecting a mapping object, as JWT only supports ' TypeError: Expecting a mapping object, as JWT only supports JSON objects as payloads. im sending correct credentials and when i print use_obj it show me user ... why is this happening and how can i fix it ? def payload_handler(user): payload = jwt_payload_handler(user) payload['is_active'] = user.is_active return payload class JWTSerializer(JSONWebTokenSerializer): def validate(self, data): user_obj = None email = data.get('email', None) username = data.get('username', None) password = data.get('password') if not email and not username: raise ValidationError("email or username is required!") if '@' in username: email = username user = User.objects.filter( Q(email=email) | Q(username=username) ).distinct() # user = user.exclude(email__isnull=True).exclude(email__iexact='') if user.exists() and user.count() == 1: user_obj = user.first() else: raise ValidationError("this username/email is not valid") if user_obj: if not user_obj.check_password(password): raise ValidationError("password is incorrect") # payload_handler(user) print(user_obj) payload = payload_handler(user_obj) print(payload) data['token'] = jwt_encode_handler(payload) return data -
Soft Delete and ForeignKey Aggregation in Django
I was adding soft-delete in Django, but encountered a problem. In the following example, I'd like to do soft delete on ChildEntity. However, when a ParentEntity only has deleted ChildEntity, the whole ParentEntity would be gone in the "exclude" query. What would be the correct one to annotate aggregation but do not filter any ParentEntity, please? class ParentEntity(models.Model): name = models.CharField() class ChildEntity(models.Model): deleted = models.BooleanField() parent = models.ForeignKey(ParentEntity, related_name='children') ParentEntity.objects.exclude(children__deleted=True).annotate( children_count=models.Count('children')) # In this collection, ParentEntity that only has deleted ChildEntity is gone :( -
Django Rest Framework read-write flat serializer using to_internal_value() and to_representation()
I've successfully implemented writable-nested-serializer following the drf documentation and also had been change its representation using to_representation() method. However, I can't seem to implement properly the to_internal_value() method so that I can have a writable-nested-serializer using the new representation. Below is my code. The update() method works properly when using PATCH. But POST and PUT doesn't work so I'm thinking I'm missing some code linking the create() and to_internal_value() methods properly. Any help would be much appreciated. /serializers.py class OrderSerializer(serializers.ModelSerializer): client = ClientSerializer() brand = BrandSerializer() class Meta: model = Order fields = ('id', 'client', 'brand', 'order_date', 'shipment_date',) def to_representation(self, obj): representation = super().to_representation(obj) client_representation = representation.pop('client') brand_representation = representation.pop('brand') for key in client_representation: representation[key] = client_representation[key] for key in brand_representation: representation[key] = brand_representation[key] return representation def to_internal_value(self, data): client_internal = {} brand_internal = {} for key in ClientSerializer.Meta.fields: if key in data: client_internal[key] = data.pop(key) else: raise serializers.ValidationError({ 'client_name': 'Omg my creation was raised.' }) for key in BrandSerializer.Meta.fields: if key in data: brand_internal[key] = data.pop(key) else: raise serializers.ValidationError({ 'brand_name': 'Omg my creation was raised no 2.' }) internal = super(OrderSerializer, self).to_internal_value(data) internal['client'] = client_internal internal['brand'] = brand_internal return internal def create(self, validated_data): client_data = validated_data.pop('client') brand_data = validated_data.pop('brand') … -
Django - UpdateView does not save to DB
My UpdateView does not save to local DB upon clicking Submit button. views.py class BHA_UpdateView(UpdateView): template_name = 'bha_test.html' context_object_name = 'bha' model = BHA_overall success_url = reverse_lazy('well_list') pk_url_kwarg = 'pk_alt' form_class = BHA_overall_Form def get_object(self, queryset=None): pk = self.kwargs.get(self.pk_url_kwarg) api = get_well_api(self.request) current_bha = BHA_List.objects.filter(well=api, id=pk)[0] return current_bha forms.py class BHA_overall_Form(forms.ModelForm): class Meta(): model = BHA_overall fields = '__all__' models.py class BHA_List(models.Model): well = models.ForeignKey(WellInfo, 'CASCADE', related_name='bha_list') bha_number = models.CharField(max_length=100) class BHA_overall(models.Model): bha_number = models.ForeignKey(BHA_List, 'CASCADE', related_name='bha_overall') drill_str_name = models.CharField(max_length=111) depth_in = models.CharField(max_length=111) bha_test.html <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" class='btn btn-primary' value="Submit"> </form> Someone told me that in UpdateView, the model and the form should refer to the same thing. So I did that, but its still not working. Here is my original question: How can I modify my code so that my form will save to my DB? -
How to fetch a matching record from an array in python?
I've a following array in python. I want to retrieve the record with an id. Is there a way to do it other than checking id field of each record by iterating through all the records. Is there a better way to do it ? [ { 'id': 'zy0Wk', 'name': 'vendor_change_order_status.txt', 'path': 'templates/messages/vendor_change_order_status.txt' }, { 'id': 'JTo8c', 'name': 'vendor_change_order_status_accepted.txt', 'path': 'templates/messages/vendor_change_order_status_accepted.txt' }, ] -
Search in django doesn't work
I am trying to have search option i my page. I have tried the method given in the standard django document in this link 'https://docs.djangoproject.com/en/1.11/intro/tutorial01/', but my search function isn't working. only the url changes from http://localhost:8000/contact this to http://localhost:8000/contact/your-contact/?q=harini but datas are not filtered and displayed. I am using django 1.11. Could anyone help me with it? Thanks in advance models.py from __future__ import unicode_literals from django.db import models class ContactModel(models.Model): name = models.CharField(max_length=200) dob = models.DateField() phone_number = models.IntegerField() gender = models.BooleanField() address = models.CharField(max_length=200) views.py from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponseRedirect, HttpResponse from django.views import generic from django.template.response import TemplateResponse from django.views.generic import CreateView from django.urls import reverse_lazy from .models import ContactModel from .forms import ContactForm class ContactView(CreateView): model_class = ContactModel form_class = ContactForm success_url = reverse_lazy('contact-thanks') initial = {'name': 'value'} template_name = 'contact/contact.html' def get(self, request, *args, **kwargs): model = self.model_class() return render(request, self.template_name, {'model': ContactForm}) def post(self, request, *args, **kwargs): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('thanks/') else: form = ContactForm() return render(request, 'contact.html', {'form': form}) class CotactlistView(CreateView): model = ContactModel template_name = 'contact/search.html' def search(request): query = request.GET['q'] t = loader.get_template('template/search.html') c = … -
How to build docker image to refer to the python library in venv
I am trying to dockerise my Django web application, which run on virtual environment venv. This is my config for my Dockerfile: FROM ppc64le/python:2.7 ENV PYTHONUNBUFFERED 1 ENV DJANGO_SETTINGS_MODULE=agricultureProj.settings.deploy ENV UWSGI_VIRTUALENV=/venv UWSGI_WSGI_FILE=agricultureProj/wsgi.py UWSGI_HTTP=:8005 UWSGI_MASTER=1 UWSGI_WORKERS=2 UWSGI_THREADS=8 UWSGI_UID=1000 >UWSGI_GID=2000 UWSGI_LAZY_APPS=1 UWSGI_WSGI_ENV_BEHAVIOR=holy RUN virtualenv venv RUN source /venv/bin/activate RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ EXPOSE 8005 COPY ./docker-entrypoint.sh / RUN chmod uog+rx ./docker-entrypoint.sh ENTRYPOINT ["sh","/docker-entrypoint.sh"] CMD ["/venv/bin/activate", "--http-auto-chunked", "--http-keepalive"] I would like to know how should I define my Dockerfile so that i can directly refer to the existing Python library and successful build and compose run my docker image for this. -
A Django website that automatically log into another website when the user click on a button and check the session status
I'm going to create a Django website where I click on a button to open up a new browser tab and automatically log in to a specific page. The website should also be able to check the logged in session status so that it can show which users are logged in at the moment. Is it possible? which Python libraries can I use for this project? -
Reverse Nested Serialization ForeignKey using DRF
I am looking to serialize models for ForeignKey relation using Django REST Framework. class A(models.Model): a_name = models.CharField(max_length=20) class B(models.Model): b_name = models.CharField(max_length=50) b1 = models.ForeignKey(A, related_name='b1') b2 = models.ForeignKey(A, related_name='b2') b3 = models.ForeignKey(A, related_name='b3') class C(models.Model): c_name = models.CharField(max_length=14) c1 = models.ForeignKey(B, related_name='c1') c2 = models.ForeignKey(B, related_name='c2') c3 = models.ForeignKey(B, related_name='c3') Using StringRelatedField: class ASerialiser(serializers.ModelSerializer): b1 = serializers.StringRelatedField(many=True) b2 = serializers.StringRelatedField(many=True) class Meta: model = A fields = ('b1', 'b2') output: [ { a_name : "Hello World", b1 : [ "b_name_1", "b_name_2", "b_name_3" ], b2 : [ "b_name_1", "b_name_2", "b_name_3" ], } ] How to serialize objects of model "C" from "A" model serializer? Should I use ForeignKey or OneToOneField? The output I'm looking for: [ { a_name : "Hello World", c1 : { b1: "c_name", b2: "c_name", b3: "c_name", }, c2 : { b1: "c_name", b2: "c_name", b3: "c_name", } } ]