Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
React Pagination Factory and Django API Pagination
My goal is to paginate the results for react-bootstrap-table2's pagination with a Django api. My problem is that the table is taking data from a results array from the api endpoint. Thus leading me to set the state with the data within the results. The api currently limits an offset of 100 per request. Instead I would need the count, next endpoint, and prev if applicable. How can I get the next bit of data from the offset? Another issue related, when I query without adding .results on setMealDashboard(data) I get undefined and it's expecting an array, despite adding results.id to the columns. How can I get around this so it's all in my mealDashboardData state? Pagination Const: const pagination = paginationFactory({ sizePerPage: 50, showTotal: true, }); My data: count: 600 next: "http://localhost:8000/api/meals/?limit=100&offset=100" previous: null results: [..... const [mealDashboardData, setMealDashboard] = useState([]); useEffect(() => { const getMealDashboard = async () => { try { const { data } = await fetchContext.authAxios.get( `/api/meals/` ); setMealDashboard(data.results); console.log(data); } catch (err) { console.log(err); } }; getMealDashboard(); }, [fetchContext]); My component: <ToolkitProvider bootstrap4 keyField="id" data={mealDashboardData} columns={columns} search > {(props) => ( <div> <div className="search float-right"> <SearchBar {...props.searchProps} /> <button type="button" className="btn" onClick={() => props.searchProps.onSearch('')} … -
how to run django project using docker
I am trying to create a docker container to run my django project. Following different other questions, I managed to obtain a successful build with docker. I have created a Dockerfile, docker-compose and I have created a local postgres database. and if I run the project from the entrypoint (chain of makemigration, migrate and runserver) the service can be reached. the problem is when I dockerize the project. my docker-compose.yml file is version: "3.9" services: db: restart: always image: postgres:12.0-alpine volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=signalcrossingrestapi - POSTGRES_USER=$POSTGRES_LOCAL_USER - POSTGRES_PASSWORD=$POSTGRES_LOCAL_PASSWORD env_file: - ./.env web: restart: always build: dockerfile: Dockerfile context: . volumes: - .:/code ports: - "8000:8000" depends_on: - db env_file: .env command: ./run.sh volumes: postgres_data: driver: local and the dockerfile is FROM python:3.8-slim # set up the psycopg2 RUN apt-get update && apt-get install -y libpq-dev gcc postgresql-client ENV PYTHONUNBUFFERED=1 ENV VIRTUAL_ENV=/opt/venv RUN python3 -m venv $VIRTUAL_ENV ENV PATH="$VIRTUAL_ENV/bin:$PATH" WORKDIR /code ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /code/ RUN pip install psycopg2==2.8.3 RUN pip install --upgrade pip && pip install --no-cache-dir -r requirements.txt RUN apt-get autoremove -y gcc EXPOSE 8000 when I execute docker-compose up --build it is successful but when I open localhost:8000 I cannot reach … -
Using Git on DigitalOcean server: error: The following untracked working tree files would be overwritten by merge
I am using Django for my site on DigitalOcean. So, I had to delete the migration files for one of my apps (accounts) and run makemigrations again. I don't really recall when or why, but it has caused this error when I pull from origin: $ git pull origin master From https://github.com/... ... error: The following untracked working tree files would be overwritten by merge: accounts/migrations/0001_initial.py Please move or remove them before you merge. Aborting Locally, my accounts app has only one migration: accounts > migrations __init__.py 0001_initial.py When I run git status on the server, I get a lot of untracked files, and I can see two migrations related to my accounts app (even though locally I only have one migration file in the accounts/migrations) as well as other untracked files (not related to accounts app): On branch master Untracked files: (use "git add <file>..." to include in what will be committed) accounts/migrations/0001_initial.py accounts/migrations/0002_alter_user_id.py ... Given that I don't want to mess with the production database, I don't wish you to change the migration files on the server to replicate the local migration files unless this does not cause any problem for my server. So, how should I resolve … -
Django form doesn't save value in multiple choice fields
I'm using Django's ModelForm and for no reason my form doesn't save the value of multiple choice fields. This is my models.py: class CaptureVersion(models.Model): id_capture = models.AutoField(primary_key=True) name = models.CharField(unique=True, max_length=50, verbose_name="Nom Disseny") int_reference_number = models.CharField(max_length=15, unique=True, blank=True, null=True, verbose_name='IRN') capture_version_id_provider = models.ForeignKey(Provider, on_delete=models.CASCADE, db_column='id_provider', verbose_name='Proveïdor') associated_register = models.CharField(max_length=150, blank=True, null=True, verbose_name='Registre associat') start_date = models.DateField(blank=True, null=True, verbose_name='Data Alta') end_date = models.DateField(blank=True, null=True, verbose_name='Data Baixa') target_size = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True, verbose_name='Regions diana (Mb)') probe_size = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True, verbose_name='Sondes (Mb)') sections = models.ManyToManyField(Section, blank=True, verbose_name="Secció") responsibles = models.ManyToManyField(Responsible, blank=True, verbose_name="Responsable/s") class Meta: ordering = ['start_date'] db_table = 'capture_version' And my forms.py: class FormulariCaptura(ModelForm): class Meta: model = CaptureVersion fields = ("name", "int_reference_number", "capture_version_id_provider", "associated_register", "start_date", "end_date", "target_size", "probe_size", "sections", "responsibles",) The problem are the fields sections and responsibles which are foreign keys. When I select one of the values of the dropdown list in the form, there's no problem and the entry is saved with no apparent errors but the value in the table for that field is -. But if I do it in the admin, it works or if I edit the entry with UpdateView. This worked yesterday and I didn't change anything... My views.py: def … -
Django - link to url from different apps redirecting to the same links
I have three apps in the project which have different templates with different URLs but one I go the someone app template page then the links on this page are showing to other app URL whereas I have different apps with different URLs name When I changed the name of templates files of every app then working fine. Please give me a solution what is the problem getting with the same name file in a different app. Thanks Admin App urlpatterns = [ path('login', views.login, name='admin_login'), path('register', views.register, name='admin_register'), path('logout', views.logout, name='admin_logout'), path('dashboard', views.dashboard, name='admin_dashboard') ] templates ----pages ------login.html ------register.html Customer App urlpatterns = [ path('login', views.login, name='customer_login'), path('register', views.register, name='customer_register'), path('logout', views.logout, name='customer_logout'), path('dashboard', views.dashboard, name='customer_dashboard') ] templates ----pages ------login.html ------register.html When I changed to templates ----pages ------customer_login.html ------customer_register.html Then working but I can not find an issue why is giving this type of error whereas I have a different app with different vies, templates, URLs, and pathname where I'm redirecting. Thanks in advance -
Passing data from javascript to python view in Django using ajax and saving it to database
I have created review section where user enter their reviews and then it gets saved to database. My problem here is ajax section, what i want is that on click of submit button the data which is stored in JavaScript variable get passed to python view in Django using ajax and get updated to MySQl. Html code of review <section> <div class="modal hidden"> <button class="exit">&times;</button> <div class="reviewer-detail"> <img class="review_img" src="{% static 'Images/Farmer3.jpg' %}"> <p class="review_name">Name:<span class="rn">Abhiraj Yadav</span></p> </div> <textarea type="text" placeholder="Enetr your review..." class="review_input" ></textarea> <button class="review_submit">Submit</button> </div> </section> <script src="http://code.jquery.com/jquery-1.10.2.js"></script> <script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> JavaScript side code const submitReview=document.querySelector(".review_submit") submitReview.addEventListener("click",function(e){ e.preventDefault() const input=inputReview.value; console.log(input) $.ajax({ url:'http://localhost:8000/FarmaHome/review', type:"GET", headers:{ 'X-CSRF-TOKEN':$('meta[name="csrf-token"]').attr('content') }, data:{'userInput':input}, success:function(){ alert(`Thankyou ${user_data.name}`); } }) }); url section from django.urls import path, include from .import views urlpatterns = [ path('', views.home), path('your-orders/', views.customerOrder), path('',include('django.contrib.auth.urls')), path('userlogin/', views.userLogin), path('register/', views.register), path('pesticide/',views.pesticide), path('fertilizers/',views.fertilizers), path('review/',views.review), ] Python view def review(request): mydb = mysql.connector.connect(host="localhost", user="root", password="windows10", database="farmaproduct") curr = mydb.cursor() sql = "select * from efarma_customer" curr.execute(sql) input = request.GET.get("userInput") try: curr.execute(f"update efarma_customer set review={input} where link_id={user_id}"); except: mydb.rollback() mydb.close() return render(request, 'efarma/home.html', {'input': input}) Any help would be appreciated thanks in advance. -
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?