Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to import some variables from django settings
I have set the DJANGO_SETTINGS_MODULE to be my settings file. Some sample lines of this settings file follow: TEST = { 'CLIENT': os.environ.get("CLIENT_NAME", "unknown"), 'ENVIROMENT': os.environ.get("ENVIROMENT", "unknown") } client_name = os.environ.get("CLIENT_NAME", "unknown") enviroment = os.environ.get("ENVIROMENT", "unknown") I then try to import the django settings by using from django.conf import settings as django_settings I am then able to print the value of the django_settings.TEST['CLIENT'] but not of the django_settings.client as I get 'Settings' object has no attribute 'client' What am I missing? To my the only difference is that TEST is a dict while client is a variable of string type. -
Passing string to server
I need to send string to the Django server. and after doing some operations with this line and return string, navigating to the page without reloading it. I did this with the help of a redirect to another page, I didn’t figure it out with Ajax server, who can tell you what is the best way to do it? -
Deploying Django for free
I created a project with django,and I want to deploy it. I prefer not to spend any money on webserver, host... Is it possible? How can I do that? By the way, I can't use Heroku. -
django clear GPU memory
I have NLP models which I am running it on GPU. Now I load the model at first django API call and keep it in the memory, as it takes time to load the model and I have to run it on multiple files. This works fine by setting the loaded model in global variable. I want to free the memory once I am done. How would I do that. I tried to do this but it didnt work as I see the same memory used when I do TOP class Unload_model(views.APIView): def post(selfself, request): global model del model torch.cuda.empty_cache() return Response([], status = status.HTTP_200_OK) I am setting up the gloabl variable like this: model = None class Predict(views.APIView): # init random seed random.seed(555) def post(self, request): for entry in request.data: # load the model global model serialization_dir = entry["serialization_dir"] params = Params.from_file(entry["config_file_path"]) if model == None: model = loadAllenNLPModelFromDisk("vocabulary", "best.th", params) cuda_device = 0 model = model.cuda(cuda_device) -
How to use ModelChoiceField in django rest framework?
I am trying to convert my form that was written earlier to django rest serializer but it does't work. Could you help me to solve this problem please? this is my form: class TripSearchForm(forms.Form): departure = PlaceModelChoiceField( queryset=Place.objects.places_for_segment(), widget=autocomplete.ModelSelect2(url="autocomplete") ) destination = PlaceModelChoiceField( queryset=Place.objects.places_for_segment(), widget=autocomplete.ModelSelect2(url="autocomplete") ) my serializer: class SearchSerializer(serializers.Serializer): departure = serializers.RelatedField(queryset=places_models.Place.objects.all(), label='departure') destination = serializers.RelatedField(queryset=places_models.Place.objects.all(), label='destination') -
Why is selenium-webdriver (LiveServerTestCase) still pointing at the wrong database?
I'm using Selenium to run some integration tests for a Django app (using postgres for the development database). I set-up the tests by creating a Model object. The tests then interact with the object through the browser (selenium-webdriver), or directly through database queries. The tests that use webdriver cannot access the Model object. The database queries can. I've come to the conclusion that webdriver is not being pointed at the correct database. I've tried using LiveServerTestCase both explicitly giving it the port and URL I want to use (localhost:8001) and using live_server_url to allow it to decide for itself. Neither have worked. Here's the form being tested - it's a simple select from a list of objects. forms.py class FooForm(form.Form): foo = forms.ModelChoice.Field( required=False, label='select', queryset=Foo.objects.all(), widget=forms.Select(), ) Here's the DB settings. settings.py DATABASES = { 'default':{ 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'app', 'USER': 'user', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '', } } Here are the tests. test.py from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.select import Select from django.test import LiveServerTestCase from app.models import Foo class BasicTestCase(LiveServerTestCase): def setUp(self): foo = Foo.objects.create(name='test_foo') self.selenium = webdriver.Firefox() super(BasicTestCase, self).setUp() def tearDown(self): self.selenium.quit() super(BasicTestCase, self).tearDown() def test_can_interact_via_db_query(self): self.assertEqual(Foo.objects.get(id=1).name, 'test_foo') def test_can_interact_via_webdriver_query(self): self.selenium.get('%s%s' … -
Best practice when add a new unique field to an existing django model
I have an existing model that looks somewhat like the following... class Resource(models.Model): id = models.AutoField(primary_key=True) We have been using this for some time, and now have ~1M instances of these Resource objects (and associated ForeignKey/else usages) in our database. I now have a need to track another ID on this model, one that I want to enforce is unique. other_id = models.IntegerField(unique=True) This other_id information is currently stored in some external CSVs, and I want to (at some point in the process) load this information in to all existing Resource instances. After adding the above field, Django's makemigrations works just fine. However when I go to apply said migration against an existing database I get an error indicating that I need to provide a default to use for all existing Resource instances. I'm sure many of you have seen something similar. What is the best approach to getting around this limitation? Some methods I have thought of... Remove the unique=True requirement apply the migration externally load in the other_id value to all existing models (through some management command, or 1-off script) add the unique=True back in and apply the migration Dump all existing data to JSON flush all tables … -
Specifiy one use allowed to edit
I am Developing a website which has a group of users that are accessing a room and only one of them can do some opeations like editing,adding I am trying to implement it with django-channels When a user send a POST or PUT request.It should be first asked if he can edit. -
Django & React behind PM2 and Gunicorn combined with Nginx
I am quite new to Django and React and to Web Development at all, I hope the following does not sound too stupid: I am using Django as a backend and React for a frontend. I am starting the react frontend using PM2 and accessing the Django backend via PM2. I also installed Nginx as a reverse proxy to redirect querys to * mydomain.toplevel/admin to the django admin * mydomain.toplevel/ to the react frontend The backend and frontend communicate via a REST api, using the DJANGO REST framework and Axios for React. My main question at the moment is: Is it possible to let the frontend and the backend communicate directly on the server, in order of not exposing the API to the internet? I guess not, because react, as a JS frontend, is executed on the client side - correct? Does this also hold if the React frontend is not served as static files (npm run-server build) but via PM2? -
How to serialize queryset result below?
I use django rawquery to get result from database: class arizakestirimi_func(ListAPIView): serializer_class = arizakestirimiserializer def get_queryset(self): queryset = isyeriarizabilgileri.objects.raw("""SELECT M.id as id,M.isyeri,DATE_PART('day',(M.tarih)::timestamp - (D.mindate)::timestamp) * 24 + DATE_PART('hour',(M.tarih)::timestamp - (D.mindate)::timestamp) + DATE_PART('minute',(M.tarih)::timestamp - (D.mindate)::timestamp) / 60 as datediff FROM arizakestirimi_isyeriarizabilgileri M INNER JOIN (SELECT DISTINCT ON (isyeri) isyeri, tarih as mindate, id as id FROM arizakestirimi_isyeriarizabilgileri ORDER BY isyeri, tarih ASC) D ON M.isyeri=D.isyeri WHERE M.durustahmini='MEKANIK ARIZA' AND M.isyeri='15400001'""") return queryset Serializer class for query result class arizakestirimiserializer(serializers.Serializer): isyeri = serializers.CharField(max_length=30) datediff= serializers.FloatField() The result json.I use ListAPIView to show json: [ { "isyeri": "15400001", "datediff": 2520.0 }, { "isyeri": "2520.0", "datediff": 700.0 }, { "isyeri": "15400001", "datediff": 704.0 } ] I want to get json: { "15400001":[ {"2520.0"}, {"700.0"}, {"704.0"} ] } -
How to send error responses back to client in django rest framework?
I am newbie to Django rest framework and trying to send custom error messages back to client, where I am using VueJS. I followed the answer given here but I am unable to receive error message on client side. client-side auth.phoneVerification(this.fullName, this.mobileNo, this.email) .then((response)=>{ console.log(response.data) }) .catch((error)=>{ console.log("Error is ", error) }) server-side serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = InterestedUser fields = ('full_name', 'phone_no', 'email') def __init__(self, *args, **kwargs): super(UserSerializer, self).__init__(*args, **kwargs) self.fields['full_name'].error_messages['required'] = 'Please provide your full name.' self.fields['phone_no'].error_messages['required'] = 'Please provide your mobile number.' self.fields['email'].error_messages['required'] = 'Please provide your email id.' views.py class UserView(GenericAPIView): serializer_class = UserSerializer def post(self, request): serializer = self.get_serializer(data=request.data) print("requested data is ", request.data) if not serializer.is_valid(): raise serializers.ValidationError(serializer.errors) print("serialiser errors are ",serializer.errors) In console I am unable to receive the message as provided by serializer.errors -
How to allow inactive user to login?
I use a custom user model(AbstractBaseUser). How to allow inactive user to login?. Model fields are email , active, admin,..... By default active= false. For email confirmation activation. But I want to allow user to login both with active= true or false. -
Can i do like this (django populate manytomanyfield)
I have 2 field for players team1player and team2player Also, i have winner and loser fields and I want to fill winner and loser fields with team1player field or team2player field Can I do it the shortest way? or should I write such code again. winner=models.ManyToManyField(Player,related_name='winner') team1player=models.ManyToManyField(Player,related_name='team1player') team2player=models.ManyToManyField(Player,related_name='team2player') winner=models.ManyToManyField(select team1player or team2player) loser=models.ManyToManyField(select team1player or team2player) -
Datatables not loading for the table containing child rows
I am trying to apply the jQuery Datatable function in my html table, which contains an another child table in 2nd row of my table. I am getting the following error in my browser's console : Uncaught TypeError: Cannot set property '_DT_CellIndex' of undefined When I had empty with no data filled, the datatable was working perfectly, while the datatable didn't work properly when I uploaded the data in it. I am confused what the matter is? {% extends 'base2.html' %} {% load static %} {% load tz humanize %} {% timezone "Asia/Kolkata" %} {% block content %} <h2 class="align-left">Previous Dispatches</h2> {% include 'classroom/teachers/dispatcher_header.html' with active='dispatches' %} <div class="card"> <table class="table table-striped mb-0 dispatches" id="dispatcherhistory"> <thead> <tr> <th>ID</th> <th>Vehicles</th> <th>Gross Weight</th> <th>Route</th> <th>Route Distance</th> <th>Route TAT</th> <th>ETD</th> {# <th></th>#} <th></th> <th></th> <th></th> </tr> </thead> <tbody> <form method="post" novalidate> {% csrf_token %} {% for plan in plan %} <tr> <td class="align-middle">{{ plan.comments }}</td> <td class="align-middle">{{ plan.pk }}</td> <td class="align-middle">{{ plan.truck_type }} {{ plan.truck_name }}</td> <td class="align-middle">{{ plan.weight }}.00 KG</td> <td class="align-middle">{{ plan.origin }}-{{ plan.destination }}</td> <td class="align-middle">{{ plan.route_distance }} KM</td> <td class="align-middle">{{ plan.route_tat }}</td> <td class="align-middle">{{ plan.etd }}</td> {# <td class="align-middle">{{ plan.eta }}</td>#} <td class="align-middle"> <button class="btn" type="button" data-toggle="collapse" data-target="#multiCollapse{{ plan.pk … -
How can I iterate through an SQL database using a function within a Django model?
I need to know how I can create a function within a Django model which iterates through a SQL database, specifically another model. My Django project contains two models, 'Accelerator' and 'Review'. The Accelerator model has a decimal field 'overall_rating', the value of which is to depend on the accumulation of values inputted into one of the Review model fields, 'overall'. To make this work, I have concluded that I need to create a function within the Accelerator model which: Iterates through the Review model database Adds the value of Review.overall to a list where a certain condition is met Calculates the total value of the list and divides it by the list length to determine the value for overall_rating The value of accelerator.overall_rating will be prone to change (i.e. it will need to update whenever a new review of that 'accelerator' has been published and hence a new value for review.overall added). So my questions are: Would inserting a function into my accelerator model ensure that its value changes in accordance with the review model input? If yes, what syntax is required to iterate through the review model contents of my database? (I've only included the relevant model fields … -
Redirect user to previous page after login in django allauth social facebook login
I am using django-allauth for social login. I am using method="js_sdk" . So it gives a popup for login. But its redirecting to profile page or home page if specified in settings. Is there a way to redirect to previous page on which user was originally. for examples if I have a page https://www.example.com/product/t-shirsts-black/ so when user login it should redirect to this page. I have read the docs but it seems they have missed it. -
Context data not being passed if called from different view function
I have this function, def event (request): all_events = Quiz.objects.filter(owner_id=request.user.pk, status="Assigned") get_event_types = Quiz.objects.filter(owner_id=request.user.pk, status="Assigned") context = {"events": all_events, "get_event_types": get_event_types, } print("context is", context) return render(request, 'classroom/teachers/calendar.html', context) and it runs fine if I pass the template as 'calendar.html'. It is supposed to draw a calendar, and also pass the context called events, which is then processed by a JavaScript function to populate the days with some data values. This is my correct working calendar.html: {% extends 'base.html' %} {% load fullcalendar_tags %} {% block content %} {% for i in events %} {{ i }} {% endfor %} {% calendar %} <script> $(document).ready(function () { var currentView = '', d = new Date(), today = d.getDay(), dow = 1; $('#calendar').fullCalendar({ header: { left: 'prev,next', center: 'title', right: 'month,agendaWeek' }, defaultDate: d, events: [ {% for i in events %} { title: "{{ i.weight}} Kg", start: '{{ i.scheduled_date|date:"Y-m-d" }}', end: '{{ i.scheduled_date|date:"Y-m-d" }}', }, {% endfor %}], navLinks: true, firstDay: 1, //Monday viewRender: function (view) { if (view && view.name !== currentView) { if (view.name === 'agendaWeek') { dow = today; } else { dow = 1; } setTimeout(function () { $("#calendar").fullCalendar('option', 'firstDay', dow); }, 10); } if (view) … -
Get queryset by using filter objects on template in django
In models: class Match(models.Model): hot_league = models.ManyToManyField(HotLeague, blank=True) In template: {% for hot_league in match.hot_league.all %} By writing match.hot_league.all in template I can get all queryset of HotLeague class. But I want to use filter here with user. Like in views we can use HotLeague.objects.filter(user=request.user). But {% for hot_league in match.hot_league.filter(user=request.user) %} is not working on template. How can I do that kind of filter in template? -
Lists are not currently supported in HTML input. in django rest API framework
My project is about a university system. 2 Custom Users named Student and Professor are defined which inherits Django User Model. There is a course Model which have ManyToMany relation with Professor model to define courses and define professor for each course. I used CreateMixinModel, UpdateMixinModel, DestroyMixinModel to Update, Create and delete courses. CRUD was applied correctly. But there was a problem in displaying Professor's information and it just return professor id. I use a nested serializer in CourseCreateSErializer to display professor information beside course info. And now I cannot edit Course Object. I want to be able to edit Course Object models.py: class Professor(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) professor_no = models.PositiveIntegerField() def get_full_name(self): return self.user.first_name def __unicode__(self): return self.user.first_name + " " + self.user.last_name def __str__(self): return self.user.first_name + " " + self.user.last_name class Course(models.Model): professor = models.ManyToManyField(Professor) name = models.CharField(max_length=100) unit = models.PositiveIntegerField() serializers.py: class CustomUserSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = ('first_name', 'last_name', 'identity_no', 'email') def create(self, validated_data): return CustomUser.objects.create(**validated_data) class ProfessorDetailSerializer(serializers.ModelSerializer): user = CustomUserSerializer() class Meta: model = Professor fields = ( 'user', 'professor_no' ) def create(self, validated_data): return CustomUser.objects.create(**validated_data) class CourseDetailSerializer(serializers.ModelSerializer): professor =ProfessorDetailSerializer(many=True) class Meta: model = Course fields = ( 'professor', 'name', 'unit', … -
How can I throw max_length error in password User form in Django?
I am trying to thrown the max length error in a User form but I didn't get this error. I found this document docs where it is wrotten the following thing: To remedy this (DoS attack), Django's authentication framework will now automatically fail authentication for any password exceeding 4096 bytes. I don't get to launch this error when I exced the 4096 bytes. How can I launch this error? I counted the number bytes in a UTF-8 counter web and I introduced 55.000 bytes but I don't get the error -
Django settings LOGIN_REDIRECT_URL dynamic based on language
Let's say I have LOGIN_REDIRECT_URL='/foo/bar/' and I am on http://127.0.0.1/en/login/ and I login successfully. I will be redirected to http://127.0.0.1/foo/bar/ resulting in losing the language prefix. What should I do in order to maintain the language code in the url? Of course, I want all the other languages codes work and also the default one just like that: http://127.0.0.1/en/login/ -> http://127.0.0.1/en/foo/bar/ http://127.0.0.1/login/ -> http://127.0.0.1/foo/bar/ http://127.0.0.1/ro/login/ -> http://127.0.0.1/ro/foo/bar/ -
How to add custom error message when using createsuperuser command in Django?
I have created a custom user model and I want email and username to be a unique field. And I am using email as my main username field. Both are unique. The issue is that when I create a "createsuperuser" I get an instant error if the email is already taken by someone but in case of username field it checks the unique condition at the end which gives an ugly Postgres unique constraint failed error. I want username field to be instantly checked like the email field. Check the images below. models.py from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.forms import ModelForm from django.utils.translation import ugettext_lazy as _ class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): """Create and save a SuperUser … -
How can I query data from database in django 2.2
I´m building a app that manage a book library and i need to retrieve data from sqlite3 database I'm using djano 2.2. And i read some books and they some like this class LanguageView(viewsets.ModelViewSet): queryset = Language.objects.get() serializer_class = LanguageSerializer class Language(models.Model): name = models.CharField(max_length=50) paradigm = models.CharField(max_length=50) ```` And my serializer class is class LanguageSerializer(serializers.ModelSerializer): class Meta: model = Language fields = ('id','name','paradigm') And i expect the output of {"id":1,"name":"Learning Python", "paradigm":"object-oriented"} but it raise a error Class 'Language' has no 'objects' member -
Looking for a small dev team [on hold]
I am currently working on a youtube application geared towards helping users gain more viewers. The way it works is by correctly selecting keywords that match well with the user’s channel data such as engagement rate, watched hours and clickrate/ clickthrough. For example, a user with 1000 subs will not benefit from using the keyword fortnite, while a larger channel might. Through the use of AI, I would like to create an app that looks over the user’s channel data and then organize the generated keywords from best to worst. I have the foundations of the project but I have spent 60+ hours on it and I still have lots more to do. If anyone would like more information or would like to join, please message me. (For anyone wondering, this app will have a premium version and people who help out will get a share from the monthly earnings.) -
How to serve a Prophet model for my Django application?
I created a model with Facebook Prophet. I wonder now what is the "best" way to access these predictions from an online web application (Django). Requirements are that I have to train/update my model on a weekly base with data from my Django application (PostgreSQL). The predictions will be saved and I want to be able to call/access this data from my Django application. After I looked into Google Cloud and AWS I couldn't find any solution that hosts my model in a way that I can just access predictions via an API. My best idea/approach to solve that right now: 1) Build a Flask application that trains my models on a weekly base. Predictions are saved in a PostgreSQL. The data will be a weekly CSV export from my Django web application. 2) Create an API in my Flask application, that can access predictions from the database. 3) From my Django application, I can call the API and access the data whenever needed. I am pretty sure my approach sounds bumpy and is probably not the way how it is done. Do you have any feedback or ideas on how to solve it better? In short: 1) Predict data …