Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there any need of otp verification in Stripe while creating a charge?
I am integrating stripe with Django. It is working fine with the test cards. All payments are done successfully without otp verification. views.py code . . . data = request.POST #post request by form card = stripe.Token.create( card={ "number": data['card_no'], "exp_month": data['exp-date'][1:].split("/")[0], "exp_year": "20"+data['exp-date'][1:].split("/")[1], "cvc": data['cvv'], } ) customer=stripe.Customer.create( name = data['fn']+data['ln'], email = data['email'], source=card, address={ 'line1': '510 Townsend St', 'postal_code': '98140', 'city': 'San Francisco', 'state': 'CA', 'country': 'US', }, ) charge=stripe.Charge.create( amount=int(data['amount'])*100, currency='usd', customer=customer, description="testing", ) . . . Is this a right way of integrating stripe? PS: I am not using stripe form and stripe js/css for this, instead i am using a normal html form. -
Integrate the text editor in django blog site
Visit the site make account if you don't have an access on it. I hope you will inspired from this most beautiful text editor, I want to integrate this type of editor in my blog where users can write their articles, how can I integrate it? I use TinyMce editor right now but it has not a better experience.. Remember one thing also tell me that, if user will upload images where the images will save? -
how to add + button for foreign key , similar to django's admin
i'm trying to implement + button for foreign key select field , if the foreign key doesnt exist instead of going to another page just pop up a form page to add new entry for the foreign key , i've implemented but its full size and dont go to the previous page when i submit the form : this is what i tried class RelatedFieldWidgetCanAdd(widgets.Select): def __init__(self, related_model, related_url=None, *args, **kw): super(RelatedFieldWidgetCanAdd, self).__init__(*args, **kw) if not related_url: rel_to = related_model info = (rel_to._meta.app_label, rel_to._meta.object_name.lower()) related_url = 'admin:%s_%s_add' % info self.related_url = related_url def render(self, name, value, *args, **kwargs): self.related_url = reverse(self.related_url) output = [super(RelatedFieldWidgetCanAdd, self).render(name, value, *args, **kwargs)] output.append('<a href="%s?_to_field=id&_popup=1" class="add-another" id="add_id_%s" onclick="return showAddAnotherPopup(this);"> ' % \ (self.related_url, name)) output.append('<img src="%sadmin/img/icon_addlink.gif" width="10" height="10" alt="%s"/></a>' % (settings.STATIC_URL, 'Add Another')) return mark_safe(''.join(output)) class BookingVisitorForm(forms.ModelForm): visitor = forms.ModelChoiceField( queryset=Vistor.objects.all().order_by('-pk'),empty_label='--------', widget=RelatedFieldWidgetCanAdd(Vistor,related_url='') ) class Meta: model = BookingVisitor fields = ['visitor','reason'] python 3 django 3.2 is there something i did wrong ? or isnt there a better way to achieve it , but when i added a new visitor it should being selected in the foreign key drop down field ! thank you in advance ... -
Getting error as -> 'NoneType' object has no attribute 'delete'
I am trying to delete the "profiles" manually using "admin" portal of the DJANGO, but when I click on delete after selecting some profiles, I am getting an error as -> 'NoneType' object has no attribute 'delete' I am using signals in my code. signals.py code:- from .models import Profile from django.contrib.auth.models import User from django.db.models.signals import post_save, post_delete def createProfile(sender, instance, created, **kwargs): if created: user = instance profile = Profile.objects.create( user = user, username = user.username, email = user.email, name = user.first_name, ) def updateUser(sender, instance, created, **kwargs): profile = instance user = profile.user if created == False: user.first_name = profile.name user.username = profile.username user.email = profile.email user.save() def deleteUser(sender, instance, **kwargs): user = instance.user user.delete() post_save.connect(createProfile, sender = User) post_save.connect(updateUser, sender = Profile) post_delete.connect(deleteUser, sender = Profile) models.py code:- from django.db import models from django.contrib.auth.models import User import uuid # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, blank = True, null = True) location = models.CharField(max_length=200, blank = True, null = True) username = models.CharField(max_length=200, blank = True, null = True) email = models.EmailField(max_length=500, blank=True, null = False) short_intro = models.CharField(max_length=200, blank=True, null=True) bio = models.TextField(blank=True, null=True) profile_image = … -
data imported from database(postgresql) appears twice in django admin panel
ive imported date from a table in my postgresql to django. As you can see all the data appears twice and it is not possible to accsses it through admin panel as it shows the following error: "get() returned more than one Coffee -- it returned 2!". In the database it all apear only once. admin panel -
Python, django filter by kwargs or list, inclusive output
I want to get get account Ids that will be associated with determined list of ids, currently I filter by one exactly id and I would like to input various Ids so I can get a Wider result. My code: from typing import List from project import models def get_followers_ids(system_id) -> List[int]: return list(models.Mapper.objects.filter(system_id__id=system_id ).values_list('account__id', flat=True)) If I run the code, I get the Ids associated with the main ID, the output will be a list of ids related to the main one (let's say, "with connection to"): Example use: system_id = 12350 utility_ids = get_followers_ids(system_id) print(utility_ids) output: >>> [14338, 14339, 14341, 14343, 14344, 14346, 14347, 14348, 14349, 14350, 14351] But I would like to input more variables avoiding to fell in a for loop, which will be slow because it will do many requests to the server. The input I would like to use is a list or similar, it should be able to input various arguments at a time. And the output should be a list of relations (doing the least number of requests to DB), example if id=1 is related to [3,4,5,6] and if id=2 is related to [5,6,7,8] The output should be [3,4,5,6,7,8] -
Django lexographic ordering on tuples with a where clause
As part of some custom cursor-based pagination code in Python Django, I would like to have the below filtering and ordering on a generic Queryset (where I don't know the table name up front) WHERE (col_a, col_b) > (%s, %s) ORDER BY (col_a, col_b) How can this be expressed in terms of the Django ORM? Note I would like the SQL to keep the tuple comparison and not have this based on AND clauses. In some previous tests, it seemed more likely that PostgreSQL would be more likely to use multi-column indexes. -
You are trying to add a non-nullable field 'language' to song without a default; we can't do that
#Get this error You are trying to add a non-nullable field 'language' to song without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: Provide a one-off default now (will be set on all existing rows with a null value for this column) Quit, and let me add a default in models.py models.py class Song(models.Model): song_id = models.AutoField(primary_key= True) name = models.CharField(max_length= 2000) singer = models.CharField(max_length= 2000) language = models.CharField(max_length= 30) tags = models.CharField(max_length= 100) image = models.ImageField(upload_to = 'docs') song = models.FileField(upload_to= 'docs') movie = models.CharField(max_length = 150, default = "None") def __str__(self): return self.name -
Allow only the owners of the parent model to create a child model when utilising generic views (django-guardian)
Currently, I have two models, Parent and Child, with a one-to-many relationship. I am using the built-in generic class-based views for CRUD upon a Parent, where I'm using a django-guardian mixin to prevent users who do not own the Parent object from doing these operations, which works well. However, I want to be able to add Children to a Parent. This works fine using a generic CreateView and a modelform, where the pk of the parent is a kwarg passed in the url. However if the user changes the pk in the URL to another user's Parent object's pk, they can add a Child object to it. I want to use django-guardian (or some other means) to prevent a user from adding a Child to another User's Parent object. Can this be done or must it be done some other way? I have got it working by validating the Parent object belongs to the current user within get_form_kwargs in the CreateView but this seems hacky, and would prefer django-guardian. (I am also not using the 'pk' kwarg in production, and instead using a different 'uuid' kwarg, but I'd like to fix this security hole nonetheless). -
Pass a list of OrderedDicts from validated_data to **kwargs
with a ModelSerializer I needed to pass multiple generic relations and it works well. However, I need to recreate many for loops within the update/create methods for it work how could I pass them as **kwargs in a function since the outcome is a list of OrederedDicts? For instance I have two models: models.py: class Translation(models.Model): """ Model that stores all translations """ content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True, blank=True) object_id = models.CharField(max_length=50, null=True, blank=True) content_object = GenericForeignKey() lang = models.CharField(max_length=5, db_index=True) field = models.CharField(max_length=255, db_index=True, null=True) translation = models.TextField(blank=True, null=True) class Tags(models.Model): """ Tags Model """ id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) DISEASE = 0 TYPE = [(DISEASE, 'disease')] type = models.PositiveSmallIntegerField(choices=TYPE) name = GenericRelation(Translation) # < ------- description = GenericRelation(Translation) # < ------- serializer.py: class TranslationSerializer(serializers.ModelSerializer): """ Translation serializer to be nested into other serializers that needs to display their translation. """ # id added to be used on create/update query only # since it is not instantiated. id = serializers.IntegerField(required=False) class Meta: model = Translation """ Fields: object_id and content_type are not required and are passed dynamically. Uncomment if needed. """ fields = ["id","lang","translation","field"] class TagsSerializer(serializers.ModelSerializer): """ Tag serializer with generic relation to field 'name' and 'description'. """ name … -
Frameworks recommended for a structural engineering web-based app
I want to make a web-app that gets user input and makes structural analysis (say finite element analysis) and presents the results with a UI that includes 3D graphics (e.g. OpenGL). An example app is skyciv for those who know, but mine will be a lot simpler at the moment. I know Python, Qt and OpenGL enough to make a desktop app for my purposes. However, I want to make the code run online and people to use it anywhere without having to install the app. Plus I want to make a subscription page. What programming languages/frameworks would you recommend me to focus on in addition to Python, Qt and OpenGL for this purpose? Would Django + React + WebGL be a good combination? Would you recommend any other 3D graphics render library other than OpenGL? Thank you. -
Is there a way to have multiple names for the same integer in django IntegerChoices
So this is what im trying to do which obviously isnt working it is giving me an error because i am setting both names to the same value which is giving me duplicate integer choices: ValueError: duplicate values found in <enum 'EventTypes'>: Launched -> ExperienceLaunched, Downloaded -> ExperienceFinishedLoading, Closed -> ExperienceClosed class EventTypes(models.IntegerChoices): ExperienceLaunched = Launched = 0, ExperienceFinishedLoading = Downloaded = 1, ExperienceClosed = Closed = 2 event = models.IntegerField(choices=EventTypes.choices) -
Javascript card search filter card overview page
So I am currently building an overview page with a lot of cards which include data such as route name, number of routes, strarting point and date. Now im trying to build a filter using javascript where the user can filter on the route name, number of routes, strarting point and date so that the user can search for the specific card. Currently I have 6 cards with data and when I type in the search input field it just deletes the first 4 cards and shows the last 2. I used some unnecessary classnames like route__text, these were just for the purpose of trying to fix my search filter. My code: Help would be greatly appreciated const input = document.getElementById('search'); input.addEventListener('keyup', search); function search() { const inputValue = input.value; console.log(inputValue.toLowerCase()); const routeContainer = document.getElementById('route'); const routeDetail = routeContainer.getElementsByClassName('route__filter'); console.log(routeDetail); for(let i = 0; i < routeDetail.length; i++) { let searchTerm = routeDetail[i].querySelectorAll(".route__parent td.route__text"); // console.log(typeof searchTerm); for(let i = 0; i < searchTerm.length; i++) { let correctSearch = searchTerm[i]; console.log(correctSearch.innerHTML.toLocaleLowerCase()); if (correctSearch.innerHTML.toLowerCase().includes(inputValue.toLowerCase())) { routeDetail[i].style.display = ""; } else { routeDetail[i].style.display = "none"; } } } } search(); <div class="route" id="route"> <div class="row"> <div class="col-12 d-flex justify-content-end mb-4"> <input type="search" … -
NOT NULL constraint failed: accounts_personalcolor.user_id
I am new to Django and have trouble making django-rest-framework API for post, inheriting APIView. I'm using a serializer, that inherits djangos ModelSerializer. I face NOT NULL constraint failed: accounts_personalcolor.user_id error whenever I try saving the serializer or model object. color.js posts image using Django rest framework as follows. function PersonalColorScreen({navigation,route}) { const {image} = route.params; console.log('uri is', image.uri); const [userToken, setUserToken] = React.useState(route.params?.userToken); const requestHeaders = { headers: { "Content-Type": "multipart/form-data" } } // helper function: generate a new file from base64 String //convert base64 image data to file object to pass it onto imagefield of serializer. //otherwise, serializer outputs 500 Internal server error code const dataURLtoFile = (dataurl, filename) => { const arr = dataurl.split(',') const mime = arr[0].match(/:(.*?);/)[1] const bstr = atob(arr[1]) let n = bstr.length const u8arr = new Uint8Array(n) while (n) { u8arr[n - 1] = bstr.charCodeAt(n - 1) n -= 1 // to make eslint happy } return new File([u8arr], filename, { type: mime }) } //random number between 0-9 function getRandomInt(max) { return Math.floor(Math.random() * max); } // generate file from base64 string const file = dataURLtoFile(image.uri, `${getRandomInt(10)}.png`) const formData= new FormData(); formData.append('img',file,file.name); console.log(file.name); //axios post request to send data // axios.post('http://localhost:8000/accounts/personalcolor/', formData,requestHeaders) … -
Check if record exists when bulk POST'ing with Django REST Framework
I have a list dictionaries which I've parsed to JSON with json.dumps(). I would now like to POST this data to my database using Django REST framework. # Example Data to POST [ { "key_1":"data_1", "key_2":"data_2", }, { "key_1":"data_1", "key_2":"data_2", }, { "key_1":"data_3", "key_2":"data_4", } ] If we imagine that all entries are unique (which isn't the case with the above example dataset), we can successfully batch POST this data with: # models.py class data(models.Model): data_1 = models.CharField(max_length=64, blank=True, null=True) data_2 = models.CharField(max_length=64, blank=True, null=True) class Meta: unique_together = (( "data_1", "data_2")) # serializers.py class dataSerializer(serializers.ModelSerializer): class Meta: model = data fields = '__all__' # views.py class dataViewSet(viewsets.ModelViewSet): queryset=data.objects.all() serializer_class=dataSerializer filter_backends=[DjangoFilterBackend] filterset_fields=['key_1', 'key_2'] def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data, many=isinstance(request.data,list)) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) # Initiating the POST request api_url="localhost:8000/app/api/" requests.post( f"{api_url}data/", data=my_json_serialised_data, headers=headers ) However, this will fail if some records already exist in the database ("fields must be unique together"). As per the example data, entries in the list will occasionally already be present in the database and I would therefore like to avoid POST'ing duplicates (based on the combination of fields in the model; I have specified unique_together to be … -
How to make sure this order is retained
I want to make know what's the best way to make sure this order is retained, I think the best thing will be to apply a function that operates on this on the fly, while sqlite retains the order, postgres doesn't it reorders it when it's saved to the database, list_of_dicts = [[{'id': '3', 'text': ' Perpetual ', 'score': 3}, {'id': '2', 'text': ' Peter Parker ', 'score': 2}, {'id': '1', 'text': ' Miles .T Morales ', 'score': 1}], [{'id': '3', 'text': 'Perpetual ', 'score': 3}, {'id': '1', 'text': 'Miles .T Morales ', 'score': 2}, {'id': '2', 'text': 'Peter Parker ', 'score': 1}], [{'id': '1', 'text': 'Miles .T Morales ', 'score': 3}, {'id': '3', 'text': 'Perpetual ', 'score': 2}, {'id': '2', 'text': 'Peter Parker ', 'score': 1}], [{'id': '3', 'text': ' Perpetual ', 'score': 3}, {'id': '2', 'text': ' Peter Parker ', 'score': 2}, {'id': '1', 'text': ' Miles .T Morales ', 'score': 1}], [{'id': '1', 'text': ' Miles .T Morales ', 'score': 3}, {'id': '2', 'text': ' Peter Parker ', 'score': 2}, {'id': '3', 'text': ' Perpetual ', 'score': 1}], [{'id': '2', 'text': ' Peter Parker ', 'score': 3}, {'id': '3', 'text': ' Perpetual ', 'score': 2}, {'id': '1', … -
Pre Populate Django Users From LDAP
I'm using Django Auth LDAP for authentication for my django app. However, the user object is not created until the user attempts to log in. So I'm trying to pre populate all the users from ldap, but currently it is not populating any fields other than name and username. Not email, not is_superuser, etc. Code to get list of usernames then attempt to populate users: from django_auth_ldap.backend import LDAPBackend l = ldap.initialize(LDAP_SERVER_URI) l.protocol_version = ldap.VERSION3 l.simple_bind(LDAP_BIND_DN, LDAP_BIND_PASS) search_filter = LDAP_USER_SEARCH_FILTER attributes = ['*'] backend = LDAPBackend() results = l.search_s(LDAP_USER_SEARCH_BASE, ldap.SCOPE_SUBTREE, search_filter, attributes) return Response(results) for query, u in results: username = u[LDAP_ATTR_USERNAME][0].decode('utf-8') user, created = backend.get_or_build_user(username, u) if created: user.save() backend.populate_user(username) log.debug(f'Pre-populate: {user}, {user.email}') How can I create all the users and have their info set correctly as if they logged in with django-auth-ldap, without them having to login? -
Get url variable and value into urlpatterns in Django
I was trying to get the variable and value of a url in urlpatterns in Django. I mean, I want to put in the address of the browser type: https://place.com/url=https://www.google.es/... to be able to make a translator. And be able to pick up the variable and value in the function that receives. At the moment I'm trying to get it with re_path like this: from django.urls import path, re_path from . import views urlpatterns = [ path('', views.index), re_path('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', views.index_traductor), ] The regex match picks it up, but I don't know how to send it as a value in a variable to receive here: from django.http import HttpResponse def index(request): return HttpResponse("flag") def index_traductor(request, url=''): return HttpResponse("%s" % url) I get a blank page. Any ideas? -
Streaming Audio Files from Django Backend to Vue.js Frontend
I'm currently building a soundboard for our Pen and Paper session and I am loading the sounds as a static source from my Django backend as new Audio(data.url). I am simply using the Django Rest Framework to handle everything about the file data, like uploads and accessing the sound files: class File(models.Model): file = models.FileField(upload_to='sound-files') filename = models.CharField(max_length=100) looped = models.BooleanField() type = models.CharField( max_length=16, choices=[('bgm', 'background music'), ('sfx', 'sound effects')], default="bgm" ) But the initial loading time for the clients may be long as it needs to load a bigger 1 hour sound file for example, so I want to stream the audio instead of load it as a src. How can I go about implementing this in Django? Do I need to use another module on top of DRF or do I need to replace DRF entirely? And can I keep the instantiation of the new Audio() in the Frontend or is a different approach required there? -
How To Fix Django "127.0.0.1 redirected you too many times. ERR_TOO_MANY_REDIRECTS" in python
Whenever I Login With Agent User. Where Agent Only Have Perms to Access Leads Page and Agent Can't See Any other pages. But When I open /lead It Raise An Error 127.0.0.1 redirected you too many times. ERR_TOO_MANY_REDIRECTS app urls.py from django.urls import path from .views import ( LeadDetailView, leadlistview,LeadCreateView, LeadUpdateView, LeadDeleteView, AssignAgentView, CatogoryListView, CatogoryDetailView, LeadCatagoryUpdateView ) app_name = "leads" urlpatterns = [ path('', leadlistview.as_view(), name='lead-list'), path('<int:pk>/', LeadDetailView.as_view(), name='lead-detail'), path('<int:pk>/update/', LeadUpdateView.as_view(), name='lead-update'), path('<int:pk>/delete/', LeadDeleteView.as_view(), name='lead-delete'), path('<int:pk>/assign-agent/', AssignAgentView.as_view(), name='assign-agent'), path('<int:pk>/category/', CatogoryDetailView.as_view(), name='lead-catagory-update'), path('create/', LeadCreateView.as_view(), name='lead_create'), path('categories/', CatogoryListView.as_view(), name='catagory-list'), path('categories/<int:pk>/', CatogoryDetailView.as_view(), name='catagory-detail'), ] app views.py from django.core.mail import send_mail from django.shortcuts import render, redirect from django.urls import reverse from django.views import generic from .models import Lead, Agent, Catagory from django.contrib.auth.mixins import LoginRequiredMixin from .forms import (LeadModelForm, LeadModelForm, CustomUserCreationForm, AssignAgentForm, LeadCategoryUpdateForm, ) from agents.mixxins import OrganizerAndLoginRequiredMixin # Create your views here. class LandingPageView(generic.TemplateView): template_name = "landing.html" def landing_page(request): return render(request, 'landing.html') class leadlistview(OrganizerAndLoginRequiredMixin,generic.ListView): template_name = "lead_list.html" context_object_name = "leads" def get_queryset(self): user = self.request.user # initial queryset of leads for the entire organisation if user.is_organisor: queryset = Lead.objects.filter( organisation=user.userprofile, agent__isnull=False ) else: queryset = Lead.objects.filter( organisation=user.agent.organisation, agent__isnull=False ) # filter for the agent that is logged in queryset = queryset.filter(agent__user=user) return queryset def … -
Installing ruamel.yaml.clib with docker
I have a small project in django rest framework and I want to dockerize it. In my requirements.txt file there is a package called ruamel.yaml.clib==0.2.6. While downloading all other requirements is successfull, there is a problem when it tries to download this package. #11 208.5 Collecting ruamel.yaml.clib==0.2.6 #11 208.7 Downloading ruamel.yaml.clib-0.2.6.tar.gz (180 kB) #11 217.8 ERROR: Command errored out with exit status 1: #11 217.8 command: /usr/local/bin/python -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-b8oectgw/ruamel-yaml-clib_517e9b3f18a94ebea71ec88fbaece43a/setup.py'"'"'; file='"'"'/tmp/pip-install-b8oectgw/ruamel-yaml-clib_517e9b3f18a94ebea71ec88fbaece43a/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(file) if os.path.exists(file) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-n2gr5j35 #11 217.8 cwd: /tmp/pip-install-b8oectgw/ruamel-yaml-clib_517e9b3f18a94ebea71ec88fbaece43a/ #11 217.8 Complete output (3 lines): #11 217.8 sys.argv ['/tmp/pip-install-b8oectgw/ruamel-yaml-clib_517e9b3f18a94ebea71ec88fbaece43a/setup.py', 'egg_info', '--egg-base', '/tmp/pip-pip-egg-info-n2gr5j35'] #11 217.8 test compiling /tmp/tmp_ruamel_erx3efla/test_ruamel_yaml.c -> test_ruamel_yaml compile error: /tmp/tmp_ruamel_erx3efla/test_ruamel_yaml.c #11 217.8 Exception: command 'gcc' failed: No such file or directory #11 217.8 ---------------------------------------- #11 217.8 WARNING: Discarding https://files.pythonhosted.org/packages/8b/25/08e5ad2431a028d0723ca5540b3af6a32f58f25e83c6dda4d0fcef7288a3/ruamel.yaml.clib-0.2.6.tar.gz#sha256=4ff604ce439abb20794f05613c374759ce10e3595d1867764dd1ae675b85acbd (from https://pypi.org/simple/ruamel-yaml-clib/) (requires-python:>=3.5). Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. #11 217.8 ERROR: Could not find a version that satisfies the requirement ruamel.yaml.clib==0.2.6 (from versions: 0.1.0, 0.1.2, 0.2.0, 0.2.2, 0.2.3, 0.2.4, 0.2.6) #11 217.8 ERROR: No matching distribution found for ruamel.yaml.clib==0.2.6 However, there is no problem … -
What is the best practice for having html tags change their style after changing URL in Django?
Suppose I have this kind of navbar, the buttons in which turn white when you click it (adding an "active" class). But if the button redirects to a new url, the navbar renders anew, and the home icon is highlighted as it is by default. How to drag that "active" class on a button after a redirect? What is the best practice in that regard? Do I ask the wrong question? -
React is not displaying Rich-Text-Content from django
I am using django as backend and react as frontend, I am using tinymce to create description in django-admin page , But react is displaying description content with html tags Ouput: <p>Best Cough Syrup</p> I used dangerouslySetInnerHTML but page is not loading any content <div dangerouslySetInnerHTML={product.description} /> Is there any way to solve this issue -
Can not implement facebook oauth into my django app
I prepared backend to imlement facebook oauth. I set up all setiings as expected in docs SOCIAL_AUTH_FACEBOOK_KEY = os.getenv("FACEBOOK_APP_KEY") SOCIAL_AUTH_FACEBOOK_SECRET = os.getenv("FACEBOOK_APP_SECRET") SOCIAL_AUTH_FACEBOOK_SCOPE = ['email'] SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = { 'fields': 'email' } AUTHENTICATION_BACKENDS = ( # Important for accessing admin with django_social 'social_core.backends.facebook.FacebookOAuth2', 'django.contrib.auth.backends.ModelBackend', ) This is my link to get facebook oauth page {{baseUrl}}/api/auth/social/o/facebook/?redirect_uri={{redirect_uri}} Redirect url matches to facebook app's ap domain When i am going to facebook oauth page i get Can't Load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings. if i didn't give needed information, ask me for it and i will add it. -
Should I store static files in a separated S3 when deploying with AWS Elastic Beanstalk?
I've got a Django app running on AWS Elastic Beanstalk. Beanstalk created an S3 bucket to store the source code, versions, etc. I've configured the S3 bucket to store also my static files. Every time I deploy a new version of the code, eb runs the collectstatic command correctly and creates the static files, but it overrides the permissions. So for every new deploy, I need to go, select the static folder and make the objects public manually. Question: Is it correct to store my static files in the same bucket, or should I create a separate one with a public policy? Question 2: If it's better to use the same bucket, how can I define a public policy for the static folder, but not the other folders such as the source code?