Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the best practice to architect tasks processing using aws?
I'm going to process background tasks such as text transmission and email transmission as lambda. I thought of three ways, which is the best way? The biggest concern is whether to directly invoke Lambda in the app or use task consumer using sqs or sns . Or do you have any suggestions?enter image description here -
Django override QuerySet for pk
I'm using djongo in order to connect my Django Rest Framework project to MongoDB, As MongoDB using _id as its primary key, I changed my models like this: from djongo import models class MyModel(models.Model): _id = models.ObjectIdField(primary_key=True) name = models.CharField(max_length=200) When I query data from database, the type of _id will be bson.objectid.ObjectId So any time I want to query anything, I should do it like this: from bson.objectid import ObjectId from myapp.models import MyModel MyModel.objects.get(pk=ObjectId('606e91bd371197379e9bf919')) # or MyModel.objects.filter(_id=ObjectId('606e91bd371197379e9bf919')) and if I use MyModel.objects.filter(pk='606e91bd371197379e9bf919') it can't find the data in database This additional ObjectId which is required for any query makes many problems because none of the pre-existing classes (like Forms, Views, Django Rest Framework Serializers, ....) act like that, so I should override all of them, and this cause many code duplications, Is there a way to override any of Q/QuerySet/Model/Model Meta Class or a wrapper or anything else to apply the additional ObjectId for querying pk/id/_id field and solve this problem? Is a better way to do this? -
problems when trying to get user's username
When I run this: from django.shortcuts import render from django.http import HttpResponse from django.contrib.auth.models import User from django.contrib.auth import authenticate, login as auth_login def login(request): if request.user.is_authenticated(): username = request.user.username else: username = None return render (request, 'login_success.html', {'username': username}) I get this error: TypeError at /login/success/ 'bool' object is not callable This is my html: {% include 'base.html' %} <text align="center">Sup {{ username }}, you're logged in!</text> What does the error mean, and how do I fix it? -
django AttributeError 'WSGIRequest' object has no attribute 'get'
//id can't found error point, and didn't search solutions AttributeError at /product/3 'WSGIRequest' object has no attribute 'get' Request Method: GET Request URL: http://127.0.0.1:8000/product/3 Django Version: 3.1.6 Exception Type: AttributeError Exception Value: 'WSGIRequest' object has no attribute 'get' Exception Location: C:\Users\vudgh\anaconda3\lib\site-packages\django\forms\widgets.py, line 652, in value_from_datadict Python Executable: C:\Users\vudgh\anaconda3\python.exe Python Version: 3.8.5 Python Path: ['C:\Pytion_WorkSpoace\oto_shop', 'C:\Users\vudgh\anaconda3\python38.zip', 'C:\Users\vudgh\anaconda3\DLLs', 'C:\Users\vudgh\anaconda3\lib', 'C:\Users\vudgh\anaconda3', 'C:\Users\vudgh\AppData\Roaming\Python\Python38\site-packages', 'C:\Users\vudgh\anaconda3\lib\site-packages', 'C:\Users\vudgh\anaconda3\lib\site-packages\win32', 'C:\Users\vudgh\anaconda3\lib\site-packages\win32\lib', 'C:\Users\vudgh\anaconda3\lib\site-packages\Pythonwin'] Server time: Thu, 08 Apr 2021 22:40:36 +0900 Error during template rendering In template C:\Pytion_WorkSpoace\oto_shop\templates\base.html, error at line 0 'WSGIRequest' object has no attribute 'get' 1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <title>{% block title %} {% endblock %}</title> 7 <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> 8 <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script> 9 10 </head> Traceback Switch to copy-and-paste view Environment: Request Method: GET Request URL: http://127.0.0.1:8000/product/3 Django Version: 3.1.6 Python Version: 3.8.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'users', 'product', 'order', 'board', 'rest_framework'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template C:\Pytion_WorkSpoace\oto_shop\templates\base.html, error at line 0 'WSGIRequest' object has no attribute 'get' 1 : <!DOCTYPE html> 2 : <html lang="en"> 3 : <head> 4 : <meta charset="UTF-8"> 5 : <meta … -
Ignore invalid foreign for django migrations?
I'm migrating an application from an old DB system to django. I've imported a bunch of legacy data. I used a script to convert the table schemas from the old system into Django models, as it had a lots of tables. Then I used another script to write the content of the old db into Django fixtures, which I then imported. That all worked fine, the data is served in the views etc. However, I now noticed that some ForeignKey in the old system were not properly identified as FK and were simply put in as Char/Int fields into the djando models. So I updated a field from IntegerField to ForeignKey, but that being legacy data I had the following issue: django.db.utils.IntegrityError: The row in table 'pickings_detpick' with primary key '17170' has an invalid foreign key: pickings_detpick.fk_ent_id contains a value '30223' that does not have a corresponding value in pickings_entpick.id. So basically, there are a number of (unsure how many yet) foreign key references that point to objects that actually do not exist in the source data (for whatever reason, I don't know the hold system much). Is there a way that I can simply tell Django to ignore those … -
Make URLfield display an error instead of just being red, with invalid validator
I have an URL-field, when I enter an invalid URL (without http) it just displays a red border around the field like so. If I click "submit" it does says "enter a valid url". Since some persons does not know, that http is required to be "valid" I want to add that as a message below, just like when calling clean_link raises an validation error. How can I do that, apart from removing the validation and add that step in clean_field instead? -
Django Redirect back two pages
I have a decorator protecting certain parts of my site. def admin_only(view): @wraps(view) def _view(request, *args, **kwargs): if not Group.objects.get(name='admin') in request.user.groups.all(): return redirect('main:unauthorized') return view(request, *args, **kwargs) return _view So if the user is not in the admin group, they are redirected to a view that renders an 'unauthorized blah blah blah template'. What I want to do is redirect the user back to where they were when they tried to access the forbidden page. I'll then use something like if not Group.objects.get(name='admin') in request.user.groups.all(): messages.error("Unauthorized blah blah blah" **redirect to where they were or home incase they used direct link** -
Django installed but startproject command doesn't work
I just installed django and when I do python3 -m django --version it prints 3.2 but when I do django-admin startproject something it doesn't do anything, neither when I only do django-admin. How can I fix this? -
DRF queryset to return specific field
I'm creating a django rest framework application with this structure (assuming imports are correct, so I omit them from the code below. models.py: class Door(models.Model): type = models.CharField(max_length=40) color = models.CharField(max_length=40) serializers.py: class DoorSerializer(serializers.ModelSerializer): class Meta: model = Door fields = ['type', 'color'] views.py: class DoorViewSet(viewsets.ModelViewSet): serializer_class = DoorSerializer queryset = Door.objects.all() def get_queryset(self, *args, **kwargs): queryset = Door.objects.all() parameter = self.request.query_params.get('type', '') if parameter: return queryset.filter(type=parameter) else: return queryset So far this behaves as intended, when I make an api call to localhost/Doors it lists all the doors. And when I make an api call to localhost/Doors/?type=big it lists all the doors that have the value "big" in their "type" field. The addition I would like to make is another parameter check which would return a list of all the unique door types that exist in the database. This can be achieved in the manage.py shell by using: Door.objects.all().values('type').distinct() My attempt was the following modifications to views.py: ... parameter = self.request.query.params.get('type', '') unique = self.request.query.params.get('unique', '') if parameter: ... elif unique: return Door.objects.all().values('type').distinct() ... My assumption was that this would return the same as Door.objects.all().values('type').distinct() when I make a call to localhost/Doors/?unique=whatever However I am getting the error: "Got … -
django post with curl , the form data always get "None"
I'm using django 3.2 view.py # Create your views here. from django.shortcuts import render from django.views.generic import View from django.http import HttpResponse class TestView(View): def post(self, request): print(request.POST.get("value")) return HttpResponse("ok") in urls.py from django.urls.conf import path from .views import TestView from django.views.decorators.csrf import csrf_exempt urlpatterns = [ path("", csrf_exempt(TestView.as_view())), ] in another terminal run curl -X POST -d '{"value "user"}' http://<ip>:5000/ request.POST.get("value") always return None -
how to give an error that the record cannot be deleted because it has a connection with the database using try/except
I am new to python and there is problem, I need the system should display a message that it is impossible to delete the record, since it has connections in the database. my code: @permission_required ('orauth.group_delete', raise_exception = True) def group_delete (request, pk): group = get_object_or_404 (Group, pk = pk) if request.method == 'POST': group.delete () return redirect ('orauth: group_list') return render ( request, 'common / confirm_delete.html', { 'title': _ ('Deleting a role'), 'object': group, }, ) -
JavaScript "Uncaught DOMException: Failed to execute 'insertBefore' on 'Node'
can anyone help me with this message error, please? "Uncaught DOMException: Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node. at HTMLButtonElement." I don't know javascript, but I need this code in my Django(a python framework) app to create a dynamic form. I pick up this code in this tutorial https://engineertodeveloper.com/dynamic-formsets-with-django/ . My template is almost identical to tutorial's template. The difference between then is that my formset have three fields to fill and the tutorial's formset(not the main form) has one field. JavaScript code by https://engineertodeveloper.com/dynamic-formsets-with-django/ : const imageForm = document.getElementsByClassName("image-form"); const mainForm = document.querySelector("#pet_form"); const addImageFormBtn = document.querySelector("#add-image-form"); const submitFormBtn = document.querySelector('[type="submit"]'); const totalForms = document.querySelector("#id_form-TOTAL_FORMS"); let formCount = imageForm.length - 1; function updateForms() { let count = 0; for (let form of imageForm) { const formRegex = RegExp(`form-(\\d){1}-`, 'g'); form.innerHTML = form.innerHTML.replace(formRegex, `form-${count++}-`) } } addImageFormBtn.addEventListener("click", function (event) { event.preventDefault(); const newImageForm = imageForm[0].cloneNode(true); const formRegex = RegExp(`form-(\\d){1}-`, 'g'); formCount++; newImageForm.innerHTML = newImageForm.innerHTML.replace(formRegex, `form-${formCount}-`); mainForm.insertBefore(newImageForm, submitFormBtn); totalForms.setAttribute('value', `${formCount + 1}`); }); mainForm.addEventListener("click", function (event) { if (event.target.classList.contains("delete-image-form")) { event.preventDefault(); event.target.parentElement.remove(); formCount--; updateForms(); totalForms.setAttribute('value', `${formCount + 1}`); } }); My Django template: <div … -
Why does Django auto_now_add fail with not null on insert or update
I am trying to implement a data warehouse. So the django system will query an api at regular intervals to update the database. I am using client ids as the primary key which might be the problem but when I do save I obviously want it to create or update. I get this error whatever I do! django.db.utils.IntegrityError: null value in column "created" violates not-null constraint So originally I just had my model like this: class PersonalTaxClient(models.Model): created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) invoice_client = models.ForeignKey(InvoiceClient, blank=True, null=True, on_delete=models.PROTECT) client_name = models.CharField(max_length=100) email = models.CharField(max_length=100) Then I tried: class PersonalTaxClient(models.Model): created = models.DateTimeField(editable=False) updated = models.DateTimeField() client_code = models.CharField(max_length=20, primary_key=True) invoice_client = models.ForeignKey(InvoiceClient, blank=True, null=True, on_delete=models.PROTECT) client_name = models.CharField(max_length=100) email = models.CharField(max_length=100) # history = HistoricalRecords() def save(self, *args, **kwargs): ''' On save, update timestamps ''' print(timezone.now()) if not self.client_code: self.created = timezone.now() self.modified = timezone.now() return super(PersonalTaxClient, self).save(*args, **kwargs) and try to update like this: >>> from sbsite.models import PersonalTaxClient >>> p = PersonalTaxClient(client_code="HHH001", client_name="Bob") >>> p.save() I get the same error. I've read about 20 other SO pages but am none the wiser..............! -
Django child models don't inherit Meta inner class
I have two Django 3.0 models, one of which is a subclass of the other: # models.py class BaseCategory(models.Model): class Meta: verbose_name_plural = "categories" class Category(BaseCategory): # fields 'n' stuff Only the Category model is registered in the Admin # admin.py @admin.register(Category) class CategoryAdmin(admin.ModelAdmin): # stuff here In the Admin, the Category model is labeled "Categorys", despite the fact that it should have inherited the Meta inner class and its verbose_name_plural attribute from BaseCategory. In fact, if I copy the same code into the Category model, # models.py class Category(BaseCategory): class Meta: verbose_name_plural = "categories" # fields 'n' stuff the model is correctly labeled "Categories" in the Admin. This indicates that the Category class is not inheriting the Meta inner class of BaseCategory. Why does a child class not inherit the Meta inner class? Is there another way for me to only specify verbose_name_plural once instead of copying the exact same code into every child of BaseCategory? -
django-mssql-backend - Invalid connection string attribute (0)
OK, I'm slowly going crazy. I want to connect Django 3 to MSSQLv15 Server. Connection works if I use Trustedconnection=yes (using win credentials), it also works on Ubuntu if I'm using FreeTDS v7.4 but it won't work in Windows if I want to use service account or personal credentials without Trustedconnection. Is it some kind of dependency issue? I have tried various library version combos, but to no avail. Error message is: conn = Database.connect(connstr, django.db.utils.InterfaceError: ('28000', "[28000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'DOMAIN\\user'. (18456) (SQLDriverConnect); [28000] [Microsoft][ODBC Driver 17 for SQL Server]Invalid connection string attribute (0)") Requiremetns.txt asgiref 3.3.4 Django 3.2 django-mssql-backend 2.8.1 djangorestframework 3.12.4 pip 20.2.3 pyodbc 4.0.30 pytz 2021.1 setuptools 49.2.1 sqlparse 0.4.1 Not working (Win) DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'db_name', 'HOST': 'hostname', 'USER': 'DOMAIN\\user', 'PASSWORD': 'pass', 'PORT': '1433', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', } } } Working (Win) DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'db_name', 'HOST': 'hostname', 'USER': '', 'PASSWORD': '', 'PORT': '1433', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', 'Trusted_Connection': 'yes', } } } Working (Ubuntu) django==2.1.0 django-pyodbc-azure-2019 DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'db_name', 'HOST': … -
Django-parler does not return translated fields in the queryset
I am making an ajax request to the server to get all the news. Here is the function in views def get_news(request): if request.method == 'GET': queryset = News.objects.all().order_by("-date_news").values() all_n = list(queryset) return JsonResponse({'queryset':all_n}) But when displaying the result, there are not enough fields in which the translation is used. My model class News(TranslatableModel): translations = TranslatedFields( title_news = models.CharField(max_length = 120), desc_news = models.TextField(null=True, blank=True), ) main_image = models.ImageField(upload_to='img/news-mebelain') date_news = models.DateField(null=True, blank=True) the response from the server comes something like this date_news: "2021-03-30" id: 40 main_image: "img/news/img1 -
I'm trying to update tasks in a database but it keeps creating new tasks
I'm trying to create a feature in the def home(request): view that updates a task if the name already exists in the database. Is this possible? The code is below and help will be much appreciated. P.S. I wrote an update function below but that also doesn't work in the way that I intend it to. The error was "expecting integer not builtin function". from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.models import Group, User, Permission from django.contrib.auth import authenticate, login, logout from django.contrib.contenttypes.models import ContentType # the user from .models import Task from .forms import TaskForm def home(request): # add new task if request.user.is_authenticated: if request.method == 'POST': name = str(request.POST['task-name']) desc = str(request.POST['task-desc']) deadline = request.POST['deadline'] task = Task(task_name=name, task_desc=desc, task_deadline=deadline) if name in Task.objects.filter(task_name=name): task.save(update_fields=['task_name', 'task_desc', 'task_deadline']) else: task.save() #messages.success(request, "You've added a task.") return render(request, 'home.html', {}) else: return render(request, 'home.html', {}) def logout_view(request): # check if user is logged in when logout button is pressed if request.POST.get('logout'): print("user has logged out") logout(request) return render(request, 'logout.html', {}) def register(request): # collects customer group from database customers = Group.objects.get(name='customers') customers.has_change_permission(request, obj=Task) customers.has_view_permission(request, obj=Task) # task_content = ContentType.object.get_for_model(Task) # permission = Permission.objects.create( # codename="can_update_tasks", # … -
Django testing Forms.FileField
I'm trying to test my Comment Form with FileField. class CommentForm(forms.ModelForm): files = forms.FileField( widget=ClearableFileInput( attrs={"multiple": True, "class": "form-control", "id": "formFile"} ), required=False, label=_("Files"), ) def __init__(self, *args, **kwargs): self.ticket = None super().__init__(*args, **kwargs) class Meta: model = Comment fields = ["body", "files"] labels = {"body": _("Comment body")} def save(self, commit=True, new_status=None): instance = super(CommentForm, self).save(commit=False) if commit: instance.save() file_list = [] for file in self.files.getlist("files") or self.initial.get("files") or []: file_instance = self.save_attachment(file=file) file_list.append(file_instance) if len(file_list) > 0: async_task(add_attachments, file_list, instance.ticket.get_pk()) Writing test without attachment upload is easy, but problem starts when I want to test my form with files. I could not test whether async_task is called, and when I try to mock files and pass them to the Form, the attachment object does not apper in test database Here is my test: @patch("myapp.forms.comments.async_task", autospec=True) def test_create_comment_with_attachment(self, async_task): file_mock = mock.MagicMock(spec=File) file_mockname = "test_name.pdf" form = CommentForm( data={ "body": "Test comment", "files": mock.MagicMock(file_mock) } ) form.ticket = self.ticket self.assertTrue(form.is_valid()) form.save() attachment = Attachment.objects.last() print(attachment) The result of printing attachment is None, while I expected my file_mock to appear. Can anyone help my with testing attachment upload? -
when exactly django query execution occures
In a technical interview a questioner asked me a weird question regarding to the execution of querysets. Suppose we have a profile model like below: class Profile(models.Model): user = models.OneToOneField('User').select_related(User) surname = models.TextField(null=True) q = Profile.object.all() or q = Profile.object.get(id=1) l = q.filter(active=True) he asked how many query execution has been happened and I replied as the python interpreter executes Profile.object.all() at the begging then one query is already done. However, he answered zero, and one if we call the query, something like this: for a in l: a.surname Is his answer true in django? another doubt was about models.OneToOneField('User'), why he didn't use django.contrib.auth.models.User and defined models.OneToOneField('User').select_related(User) -
Image not loading on a class based view DJANGO for Twitter Card
I am trying to load the image on Twitter card and i am using 'SITE_PROTOCOL_URL': request._current_scheme_host, in function based views it is working well but in a class based view its not loading. I tried different ways but still doesnt work and i am stuck on it here is my code in view: def category(request,slug,pk): query_pk_and_slug = True katego=Kategori.objects.all() kategorit=Kategori.objects.get(title=slug, fotot_e_kategoris=slug) lajmet=Lajmet.objects.filter(kategorit=kategorit, verified=True).order_by('-data_e_postimit') lajms=Lajmet.objects.filter(kategorit=kategorit, verified=True).order_by('-data_e_postimit')[3:] lajmets=Lajmet.objects.filter(kategorit=kategorit, verified=True).order_by('-data_e_postimit')[7:] sponsor=SponsorPost.objects.all().order_by('-data_e_postimit') paginator = Paginator(lajmets, 15) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request,'main/category-news.html',{ 'SITE_PROTOCOL_URL': request._current_scheme_host, 'lajmet':lajmet, 'kategorit':kategorit, 'katego': katego, 'lajms': lajms, 'page_obj': page_obj, 'sponsor':sponsor }) class LajmetListView(ListView): model = Kategori model = Lajmet template_name = 'main/lajme-home.html' # <app>/<model>_<viewtype>.html context_object_name = 'lajmets' query_pk_and_slug = True def get_context_data(self, **kwargs): context = super(LajmetListView, self).get_context_data(**kwargs) context['lajmet'] = Lajmet.objects.order_by('-data_e_postimit').filter(verified=True) context['katego'] = Kategori.objects.all() context['shikime'] = Lajmet.objects.all().order_by('-shikime') context['SITE_PROTOCOL_URL'] = self.request._current_scheme_host return context And Template : {% if object.slug in request.path %} <title>{{object.titulli}}</title> <meta name="twitter:card" value="summary_large_image"> <meta name="twitter:site" content="@gazetarja_"> <meta name="twitter:creator" content="@SimonGjokaj"> <meta name="twitter:title" content="{{object.titulli}}"> <meta name="twitter:description" property="og:description" content="{{object.detajet|striptags|truncatewords:30}}"> <meta name='twitter:image' content="{{SITE_PROTOCOL_URL}}{{object.fotografit.url}}"> {% elif request.path == '/' %} <title>Portali Gazetarja - LAJMI FUNDIT</title> <meta name="twitter:card" value="summary_large_image"> <meta name="twitter:site" content="@gazetarja_"> <meta name="twitter:creator" content="@SimonGjokaj">' <meta name="twitter:title" content="Portali Gazetarja - LAJMI FUNDIT"> <meta name="twitter:description" content="Gazetarja i'u sjell në kohë reale, sekond pas sekonde informacione … -
How can I put 2 views in one template? Django
To put multiple forms in one view we are using request.POST.get(name argument of form), but When I am doing that with my register and login page than the login page is working, but I cant see the register form. The problem is to check if request is POST and than return the result for each case. def index(request): # login view if request.user.is_authenticated: return render(request, 'authenticated.html') else: if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return redirect('index') else: messages.error(request, 'Username or password is incorrect, try again!') return render(request, 'index.html') def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST or None) if form.is_valid(): form.clean_email() form.save() username = form.cleaned_data.get('username') messages.success(request, f'Successfully created account for {username}') return redirect('index') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) Html for login and registration <form method="post" name="login"> {% csrf_token %} <input type="text" name="username" placeholder="username"> <input type="password" name="password" placeholder="password"> <input type="submit" value="Login Yeah!"> </form> <form method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Sign Up"> </form> -
How to access multiple Data from jquery class to another input field to extract using python
kindly check out this image for further proceedings. Here we had used a jquery function to do the multiple CC. and we want to access those data to the second field from there will be stored to DB using python. -
How to redirect to an authenticated view with access token from another app in Django?
I have a Django website with two apps running on it. On app 1 the user receives an auth token and is supposed to be redirected to app 2 with said token. App 2 requires authentication in all views through APIView's permission_class "IsAuthenticated". app2/urls.py: app_name = 'app2' urlpatterns = [ path('',views.waitingroom_view.as_view(), name = 'waitingroom_index'), path('authenticated/',views.authentication_view.as_view(), name ='authentication') ] app2/views.py: class waitingroom_view(APIView): def get(self, request): return redirect('app1/index') My code correctly authenticates the user by giving them authentication tokens (refresh and access tokens) through a requests.post function: app1/views.py: def get_authentication_tokens(request, username, password): #BEWARE: hardcoded URL url = 'http://127.0.0.1:8000/api/token/' postdata = { 'username': username, 'password': password, } r = requests.post(url, data=postdata) tokens_json = r.json() #splits the respective tokens into 2 variables: "refresh" and "access" refresh_token = tokens_json['refresh'] access_token = tokens_json['access'] return access_token, refresh_token response = requests.get('http://0.0.0.0:8000/authenticated', auth=BearerAuth(access_token)) return HttpResponse(response) This returns a .html page that requires an auth token to access. However, the return is on app 1 instead of redirecting to app 2 with auth token. How do I redirect to an authenticated view (app 2) from another app (app 1) (that generated the auth token)? -
django model select_related or prefetch_related child model
Newbie here, I have two models which are below class ReceipeMaster(models.Model): receipe_type = models.CharField(max_length=50, choices=TYPE_OPTIONS, default=TYPE_OPTIONS[0]) item = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='receipe') units = models.IntegerField(default=1) status = models.BooleanField(default=True) class ReceipeDetail(models.Model): master = models.ForeignKey(ReceipeMaster, on_delete=models.CASCADE, related_name='items') item_type = models.ForeignKey(Item_type, null=True, on_delete=models.PROTECT) item = models.ForeignKey(Item, on_delete=models.PROTECT) quantity = models.IntegerField() I have a detailed view DetailView class ReceipeDetailView(PermissionRequiredMixin, DetailView): permission_required = 'item_management.view_receipemaster' model = ReceipeMaster template_name = 'receipes/show.html' context_object_name = 'receipe' I would like to prefetch_related or select_related on the ReceipeMaster model and as well as the ReceipeDetail model. Simply prefetch on both models. Regards -
What is the best video storage solution
I have an application which connects to Instagram API and pulls massive amount of data everyday. My next challenge is to pull and save many Instagram users stories to a storage, then let my application users to see/view those stories in my django web app. I need to save nearly 50 GB of short videos (stories) everyday This makes nearly 20 TB of data for a year, so the storage must be at least that big The amount of stories that will be watched per day on my web app will be < 1000 (less than 1 GB) I don't have any experienced developers/engineers around me, so I do my own research about the subject. Azure Blog Storage looks like the solution that fit my needs but also a very expensive one (200-400$ per month). I have experience with Postgres and MySQL databases but not with Cloud services like Google or Azure, so any links, advices and tips are appreciated highly.