Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
check if string matches first n characters of regex
I have a python site built in Django where a user will be uploading files that they may or may not have permission to add. The permissions are created through a series of regex patterns (there is over 1000). At one point in my site I have a place for the user to view their permissions (using a search filter and a list). However what I want to do is if the user types in a string and the string matches any part of each regular expression. I want it in the list. Right now I have if(filter.match(pattern)) { //add pattern to list } I have also tried searching instead of matching. An example of what I am looking for: If I have a list of regex patterns: ^(12345678)\.(txt)$ ^(qwertyuiop)\.(txt)$ ^(qwerty)\.(txt)$ ^(23456)\.(txt)$ if the user were to enter qwert the list would show ^(qwertyuiop)\.(txt)$ and ^(qwerty)\.(txt)$, whereas if the user entered qwertyu the list would only show ^(qwertyuiop)\.(txt)$. Similarly if the user entered 234 the list would show ^(12345678)\.(txt)$ and ^(23456)\.(txt)$ but if the user entered 1 the list would only show ^(12345678)\.(txt)$. Is it possible to accomplish this? If so how would I manage it? Thanks for the Help! -
Vue.js - Flask vs Django
I am a total newb to node/js/vue/react/yadda yadda. I am trying to follow blogs on setting up Vue with Flask (i want pretty flask sites!) but they are all inconsistent and confusing. I have Flask experience so i would love to use Flask backend but I am getting very discouraged that I've been working for 6 hours and have yet to even have a basic site setup. Is it worth it to try Django? Should I ditch python all together? I am frustrated, I dont have anywhere else to ask for advice so I am turning to SO. Thanks so much. There should be a "DESPERATION" tag for folks like me posting to SO in desperation :). -
Django Rest Framework tests fail and pass, depending on number of functions
I have a test class in Django Rest Framework which contains a function which passes the test if it is the only function in the class, or fails if it is one of two or more functions. If I run the below code as is, i.e. def test_audio_list(self) function remains commented out, the test passes as per the two assert statements. If I uncomment def test_audio_list(self) function and run the tests, the def test_audio_retrieve(self) function will fail with a 404 whilst def test_audio_list(self) will pass. Here is my full test case (with def test_audio_list(self): commented out). class AudioTests(APITestCase): # setup a test user and a factory # factory = APIRequestFactory() test_user = None def setUp(self): importer() self.test_user = User(username='jim', password='monkey123', email='jim@jim.com') self.test_user.save() # def test_audio_list(self): # """ # Check that audo returns a 200 OK # """ # factory = APIRequestFactory() # view = AudioViewSet.as_view(actions={'get': 'list'}) # # # Make an authenticated request to the view... # request = factory.get('/api/v1/audio/') # force_authenticate(request, user=self.test_user) # response = view(request, pk="1") # # self.assertContains(response, 'audio/c1ha') # self.assertEqual(response.status_code, status.HTTP_200_OK) def test_audio_retrieve(self): """ Check that audo returns a 200 OK """ factory = APIRequestFactory() view = AudioViewSet.as_view(actions={'get': 'retrieve'}) # Make an authenticated request to the … -
how i do post request with python-requests-library, if in my model i have images field
i need a help, i creating telegram bot , bot get to api post request, and in my model i have images field, when i do post request, i got a fail "bad request" 400, how i can fix this problem? requests.post(url='http://127.0.0.1:9999/api/create/',data={ 'title':message_title.get(message.chat.id),'images': message_photo.get(message.chat.id), 'lot': message.location.latitude, 'lang': message.location.longitude, }) "POST /api/create/ HTTP/1.1" 400 103 it's error -
Django function view to update two templates (current and base)
Django Beginner. I have a functioning Django app (models, views, urls, templates) similar to what you can see in tutorials. I would like to return some debugging and user information (e.g. if an item already exists in a table) into a terminal-like section in my base.html. Inside my standard view function call (turning an uploaded csv file to pandas and generating inserts into my normalized tables) I added a 2nd render(request,...) that sends a dictionary to my base.html. def bulkinsert(request): data=None context=None if request.method== "POST" and request.FILES['myfile']: myfile = request.FILES['myfile'] df=pd.read_csv(myfile ) data_html=df.to_html() context={'data': data_html } m='' # now read each row and insert lot, sublot, ... for index, row in df.iterrows(): if pd.notna(row['lot']): lotname=row['lot'] ... # check existence of this lot f1=Lot.objects.filter(lotname=lotname).count() if f1==0: m+='\n Lot did not exist yet, inserting ...' b1=Lot(lotname=lotname) b1.save() else: m+=f'\n Lot {lotname} already exists' ... c2={ 'memo': m} render(request, 'lenses/base.html',c2) return render(request, 'bulkinsert.html',context) else: form=UploadFileForm() data=None context=None return render(request, 'bulkinsert.html',context) What do I have to add to my base.html to pass that dictionary (c2) into the desired html-section? So far I have just: {% block c2 %} <p>{{ memo }}</p> {% endblock %} but the page does not update as I expected. -
Why use UniqueTogetherValidator over Django's default validation behavior?
I have a Django model defined with a unique_together relationship defined between name and address, shown below: class Person(models.Model): name = models.CharField(max_length=255, default='', null=False) address = models.CharField(max_length=255, default='', null=False) class Meta: unique_together = ('name', 'address') I also have a Django REST Framework serializer with a UniqueTogetherValidator describing the same constraint as defined in the model, shown below: class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person fields = ( 'name', 'address', ) validators = [ UniqueTogetherValidator( queryset=Branch.objects.all(), fields=['name', 'address'] ) ] While testing this constraint, I noticed that the exact same behavior is exhibited whether or not I have the UniqueTogetherValidator added to the PersonSerializer. The same error message is returned whether or not I include this (due to the unique_together defined on the model). My question is: what is the reason for explicitly declaring validators on the serializer if the behavior is performed behind the scenes? I did notice you can change the error message, but this seems like quite a bit of boilerplate for solely manipulating an error message for violating a unique_together constraint. Is there a broader reason for utilizing these validator classes that I'm missing? -
error: "int() argument must be a string, a bytes-like object or a number, not 'list'" in decorator @action
Good afternoon I am doing an @action decorator to a viewset in django rest to filter my model by a field and some values in an list and thus obtain (properties) values that will be consumed in the api rest. My code is as follows: class EquiposViewSet(viewsets.ModelViewSet): queryset=Equipo.objects.all() serializer_class=EquipoSerializer @action(methods=['get'], detail=False, url_path='equipos-alarm', url_name='equipos_alarm') def equipos_alarm(self, request): # pylint: disable=invalid-name queryset=Equipo.objects.filter(id_equipo=[106,107,156,157]) return Response ( { 'id_equipo':equipo.id_equipo, 'nombre_equipo':equipo.nombre, 'hora_ospf':equipo.recorrido_ospf, 'hora_speed':equipo.recorrido_speed, } for equipo in queryset ) and the error that returns me is the following: int() argument must be a string, a bytes-like object or a number, not 'list' How can i fix this? -
Getting Object based on its ID
Setup I am trying to write a DeleteView that will delete an object based on its Id. The object is a journal and I want to reference the Journal that the user is currently located in. So for example if User1 is in Journal "Work" I want to delete that specific one based on journal Id and not anything else. My understanding is that Django creates an ID fields (Autofield) for each model. Error This is my current view: class DeleteJournal(LoginRequiredMixin, DeleteView): model = Journal tempalte_name = 'delete_journal.html' success_url = reverse_lazy('home') def get_object(self, queryset=None): id = self.kwargs['id'] return self.get_queryset().filter(id=id).get() The error I receive is this: What is the solution to this and why is it not working? Thanks a ton in advance, really appreciate anyone looking at this. -
Adding file upload widget for BinaryField to Django Admin
We need to store a few smallish files to the database (yes, I'm well aware of the counterarguments, but setting up e.g. FileField to work in several environments seems very tedious for a couple of files, and having files on the database will also solve backup requirements). However, I was surprised to find out that even though BinaryField can be set editable, Django Admin does not create a file upload widget for it. The only functionality we need for the BinaryField is the possibility to upload a file and replace the existing file. Other than that, the Django Admin fulfills all our requirements. How can we do this modification to Django Admin? -
List or table with field names as a column other than header
I am wondering whether it is do-able to make a list or table or any other solutions like:          Time 1    Time 2 FieldName1   a_Value1   b_Value1 FieldName2   a_Value2   b_Value2 FieldName3   a_Value3   b_Value3 The reason I want this is that I have 30+ fields, which will be ugly and not user-friendly if using an ordinary table. The structure of this is like 30 rows by 3 columns. -
how to add two fields as foreign key to a table?
I have two tables "team" and "match". every team can be on different matches and every match contain two or more teams and so it's a manytomany relation. here is my match model: class Match(models.Model): result = models.CharField(max_length=10, default='') winner = models.?????? team = models.ManyToManyField(Team, related_name='team') referee = models.ForeignKey(User, on_delete=models.PROTECT, related_name='referee') the winner of every match is also a team but I don't know how to handle it. should I define it as foreign-key to team table? what is the right way? -
Django settings.py
At my project login, some settings.py environment variables are loaded to enable some behaviors: unit_id = settings.COMPANY When another user logged in the system changes the value of this variable, through a function, it reflects in all other users who are already active: settings.COMPANY = "coke" in this case, all users will see "coke" in settings.COMPANY. I believed this would be in memory and would only apply to the user section in question, because I did not write in the physical file. I wonder if this is how Django handles the settings.py environment variables: Does it propagate dynamically to all instances opened by all users? -
how to control the for loop if the value is already detect?
\html <select id="payments" name ="payments" onchange="payment(this.value)"> <option value="0" name ="yearlvllist">-- Payment Type --</option> {% for paymentschedule in payment %} <option value="{{paymentschedule.Payment_Type.id}}" name ="payments">{{paymentschedule.Payment_Type}}</option> {% endfor%} </select> \views def scheduleofpayment(request): payment = ScheduleOfPayment.objects.all().filter(Education_Levels=paymentsid).order_by('Display_Sequence') return render(request, 'accounts/scheduleofpayment.html', {"payment":payment}) \models class ScheduleOfPayment(models.Model): Pending_Request = [ ('Active', 'Active'), ('Inactive', 'Inactive'), ] Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True, null=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE,blank=True, null=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, blank=True, null=True) Display_Sequence = models.IntegerField(blank=True, null=True) Date = models.DateField(null=True,blank=True) Amount = models.FloatField(null=True, blank=True) Remark = models.CharField(max_length=500,blank=True, null=True) Status = models.CharField(max_length=500, null=True, choices=Pending_Request,blank=True) def __str__(self): suser = '{0.Education_Levels}' return suser.format(self) this is the image from my admin-site admin-site this is the result of what i filter in schedule of payment user My problem is how to control the looping of monthly in html template? without deleting the database. do you have an idea guys ? -
What is the source of slow response time on client when server is fast, in Python web app hosted in Azure
I have a simple Python web app hosted in Azure. Here are the details: Azure App Service for Linux (Basic Service Plan - B1 with 1 core) Django framework Postgres backend via Azure Databases for PostgreSQL Uses Vue on the client-side All services are located in the same resource group Problem It is a simple app and the database queries take about 30ms, including the time to fetch. However, the app is performing quite slowly.The initial load time of the SPA in the client is around 10s, with subsequent requests taking around 7-8s. Troubleshooting I took a look at the response times in application insights and it seemed acceptable to me. I then took a look at the requests for a single page load. I noticed that while the individual responses for each API call were fast, there one about 1s between each request. I then tried various gunicorn configurations, changing the workers & threads. I settled on 1 worker with 4 threads. This improved performance to 1.5-2s per page load after the SPA loads. This is still not quite satisfactory, especially considering that applications insights suggests that the median response time is 160ms. I then scaled the app all … -
How to get related values in 3 Models Django
I have 3 models, Order, OrderDetail and Sale, in Sale I save the Order "id", and in the Sale DetailView I want to show all OrderDetails "products" related to that Order. My models: class Pedido(models.Model): total = models.DecimalField(max_digits=10, decimal_places=2, default=0) fecha = models.DateField(default=datetime.now, null=True, blank=True) estado = models.CharField(max_length=20, default='Pendiente') cliente = models.CharField(max_length=50, default='Agregue Cliente') observacion = models.CharField(max_length=200, null=False, default='Ninguna') class DetallePedido(models.Model): pedido = models.ForeignKey(Pedido, db_column='pedido_id', on_delete=models.SET_NULL, null=True) producto = models.ForeignKey(Producto, db_column='producto_id', on_delete=models.SET_NULL, null=True, verbose_name='Productos') cantidad = models.DecimalField(max_digits=10, decimal_places=0, default=1) precio = models.CharField(max_length=200, default=0) class Venta(models.Model): fecha = models.DateField(default=datetime.now, null=True, blank=True) pedido = models.ForeignKey(Pedido, db_column='pedido_id', on_delete=models.SET_NULL, null=True) total = models.CharField(max_length=200, default=0) cliente = models.CharField(max_length=100) nit = models.CharField(max_length=10) In the Order DetailView im getting all the "products" in OrderDetail like this: {% for producto in pedido.detallepedido_set.all %} code.. How can I show all the products related in the Order saved in the Sale? -
paginator reset query as i change page
I am developing an app in Django. I have a template in which are displayed data from my model. The template has a search bar and also a paginator. The problem is that, when I run a query (let's say I search for the word "home"), it shows the filtered results for page one, but as I click on my paginator to get to the next page, the query gets reset, and I get page 2 of unfiltered data (entire data). How can I fix it? Here is my paginator code: <nav aria-label="..."> <ul class="pagination"> {% if all_entries.has_previous %} <li class="page-item"> <a class="page-link" href="?page=1">&laquo; first</a> </li> <li class="page-item"> <a class="page-link" href="?page={{ all_entries.previous_page_number }}">{{ all_entries.previous_page_number }}</a> </li> {% else %} <li class="page-item disabled"> <a class="page-link" href="#" class="page-item disabled">&laquo; first</a> </li> <!-- <li class="page-item disabled"></li> <a class="page-link" href="#" class="page-item disabled">previous</a> </li> --> {% endif %} <li class="page-item active"> <a class="page-link" href="#">{{ all_entries.number }}<span class="sr-only">(current)</span></a> </li> {% if all_entries.has_next %} <li class="page-item"> <a class="page-link" href="?page={{ all_entries.next_page_number }}">{{ all_entries.next_page_number }}</a> </li> <li class="page-item"> <a class="page-link" href="?page={{ all_entries.paginator.num_pages }}">Last [ {{ all_entries.paginator.num_pages }} ] &raquo;</a> </li> {% else %} <!-- <li class="page-item disabled"></li> <a class="page-link" href="#" class="page-item disabled">next</a> </li> --> <li class="page-item disabled"> <a class="page-link" … -
Python social auth: default Django backend doesn`t authenticate users
I want to add authentication with different auth providers to my Django project, so I decide to use python-social-auth. I’ve configured my settings.py as mentioned in an official docs. And Django ModelBackend never authenticates a user! settings.py: AUTHENTICATION_BACKENDS = ( 'social_core.backends.backends.GithubOAuth2', 'django.contrib.auth.backends.ModelBackend', ) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR.child('templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] SOCIAL_AUTH_USER_MODEL = 'users.models.CustomUser' SOCIAL_AUTH_URL_NAMESPACE = 'social' SOCIAL_AUTH_GITHUB_KEY = '...' SOCIAL_AUTH_GITHUB_SECRET = '...' # don`t want to create users SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) urls.py: urlpatterns = [ ... path('social/', include('social_django.urls', namespace='social')), ... ] template: <a href="{% url "social:begin" "github" %}">Login with GitHub</a> It happens cause social_core doesn`t put a username and password arguments to the authenticate method, ModelBackend always fails in getting users. Passed arguments are backend instance, storage instance and response from GitHub. Ok, so I decided to make my own auth backend. class SocialAuth(ModelBackend): def authenticate(self, request, **kwargs): backend = kwargs.get('backend') response = kwargs.get('response') username = backend.get_user_details(response)['username'] return UserModel.objects.get_by_natural_key(username) And it works well then I get some errors with user.social_user attribute, but I guess it`s too much for one question. So, why all … -
CSS changes not appearing - Django
When I make new changes to my css the new changes are not showing. If i delete a style it still shows and if I delete my <link> tag all the styles disappear. I can edit styles with inspect element but the same changes do not show if I edit my style sheet. This is strange because it shows old styles only. settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') base.html {% load static %} <link rel="stylesheet" href="{% static 'css/style.css' %}"> -
Rendering a pandas dataframe on-page in django
I have created a page with Django where you can upload an excel file and it will save into the /media folder. Once it's uploaded, there is a page that shows a table of the uploaded files. I have added a 'View' button, and the expected behavior would be to pd.read_excel, then do a df.to_html, and then render that html on the same page. There have been several other questions regarding how to do this, but they don't seem to fit my specific use case. Any help you can provide on making the function and rendering it would be greatly appreciated! Thank you. -
django form: CheckboxSelectMultiple's id_for_label does not work
I want to customize my label style, so I overwrite {{ form }} in my html template with a for loop through all choices. But I found I lost label 'for' attribute and 'id' of the input for each choice after using for loop. Old codes: html template: {% block form %} <button class="checker">Uncheck all</button> <button class="allChecker">Check all</button> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form }} <br/> <input type="submit" value="Submit"> </form> {% endblock %} my form: class RerunForm(forms.Form): items = ItemStatus( queryset=models.Container.objects.none(), widget=forms.CheckboxSelectMultiple(attrs=dict(checked='')), help_text="Select requirements/objectives that you want to rerun.", ) def __init__(self, rerunqueryset, *args, **kwargs): super(RerunForm, self).__init__(*args, **kwargs) self.fields['items'].queryset = rerunqueryset class ItemStatus(models.ModelMultipleChoiceField): def label_from_instance(self, obj): if '_' not in obj.name: return "{} ({})".format(obj.name.replace('-r1', '').replace('-s1', ''), obj.state) else: return ". . . {} ({})".format(obj.name.replace('-r1', ''), obj.state) New Codes: html template: {% block form %} <button class="checker">Uncheck all</button> <button class="allChecker">Check all</button> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <ul id="id_items"> {% for value, label, item in form.items.field.choices %} <li> <label for="{{ form.items.id }}"> <input type="checkbox" value={{ value }} name="items" id="{{ form.items.auto_id }}"> <span class="listItem-{{item.state}}">{{ label }}</span> </label> </li> {% endfor %} </ul> <br/> <input type="submit" value="Submit"> </form> {% endblock %} new form: class RerunForm(forms.Form): items = ItemStatus( queryset=models.Container.objects.none(), widget=forms.CheckboxSelectMultiple(attrs=dict(checked='')), help_text="Select … -
Save data in 1 api post call using django rest framework
I have 3 tables in a sequence with foreign keys like this 1st table class Orders(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, blank=True, null=True) order_number = models.AutoField(primary_key=True) total_amount = models.DecimalField(max_digits=10, decimal_places=2) 2nd table is which will keep record of articles for sale class OrderArticle(models.Model): order = models.ForeignKey(Orders, on_delete=models.CASCADE) article = models.ForeignKey(Articles, on_delete=models.CASCADE) article_quantity=models.IntegerField(default=0) prize=models.DecimalField(max_digits=10, decimal_places=2) 3rd table is option of Articles which can be added to articles every article have its own options class OrderArticleOptions(models.Model): article_option = models.ForeignKey(ArticlesOptions, on_delete=models.CASCADE) order_article = models.ForeignKey(OrderArticle, on_delete=models.CASCADE) article_option_quantity = models.IntegerField(default=0) price = models.DecimalField(max_digits=10, decimal_places=2) Now I want to add data in this using Django rest framework .I am adding data into Order table like this Serilizer.py is class OrderSerializer(serializers.ModelSerializer): restaurant=RestaurantSerializer(required=False) article=ArticlesSerializer(read_only=True, source='orderarticle_set' , many=True) total_amount=serializers.DecimalField(required=False,max_digits=5, decimal_places=2) tableid=serializers.IntegerField(required=False) class Meta: model = Orders fields = [ 'order_number' , 'tableid' , 'total_amount' , 'ordertime' , 'order_status' ,'restaurant', 'article' ,] def create(self, validated_data): tableid = validated_data.get('tableid') total_amount = validated_data.get('total_amount') order_status = validated_data.get('order_status') restaurant = validated_data.get('restaurant') order_obj = Orders.objects.create(tableid=tableid, total_amount=total_amount,order_status=order_status, restaurant=restaurant ) return order_obj And my view.py is class CreateOrderApi(APIView): def post(self, request,restid): serializer = OrderSerializer( data=request.data) if serializer.is_valid(): obj_order = serializer.save(restaurant=Restaurant.objects.get(id=restid)) So Now I want to add data into all three tables , relation is In one order I … -
Upload multi img to 1 post on Django ? How do that?
I want to upload multi img to 1 post on Django. I used ImageField in models.py. But it's just can upload 1 image to 1 post. How can i upload multi image to 1 post with Django or someways to solved that problem. Thank you so much. -
dataSource in mat Table using Angular Material in Angular 8 get method
i try to create a Mat Table using Angular and Django for build a filter and pagination method,etc. the thing is this i'm using Django like backend and Angular Fronted, and i have the method Get ,Insert, Alter and Delete. all that method is work 100% ,but i don't have idea how i can make the filter using that methods for build the filter and pagination buttons. i need know, if i can build a filter method for example using only the fronted or i need both for make the method. service .ts baseurl = "http://127.0.0.1:8000"; constructor(private http: Http, private httpClient: HttpClient) { } private headers = new Headers({ 'Content-Type': 'application/json', Authorization: `JWT ${localStorage.getItem("token")}` }); getDoctores(): Promise<Doctor[]> { return this.http.get(this.baseurl + '/doctor?format=json', { headers: this.headers }) .toPromise() .then(response => response.json() as Doctor[]) } deleteDoctor(id: number): Promise<void> { const url = `${this.baseurl + "/doctor"}/${id}`; return this.http.delete(url, { headers: this.headers }) .toPromise() .then(() => null) } createDoctor(d: Doctor): Promise<Doctor> { return this.http .post(this.baseurl + "/doctor", JSON.stringify(d), { headers: this.headers }) .toPromise() .then(res => res.json() as Doctor) } updateDoctor(doctores): Observable<any> { const body = { nombreDoc: doctores.nombreDoc, apellidoDoc: doctores.apellidoDoc, rutDoc: doctores.rutDoc, release_date: doctores.release_date, direccionDoc: doctores.direccionDoc, telefonoDoc: doctores.telefonoDoc }; return this.http.put(this.baseurl + '/doctor/' + … -
How can I make a Google Map marker redirect to a URL?
Here is my html: {% extends 'base.html' %} {% block title %}Home{% endblock %} {% block content %} <style> /* Set the size of the div element that contains the map */ #map { height: 700px; /* The height is 400 pixels */ width: 100%; /* The width is the width of the web page */ } </style> <!--The div element for the map --> flavor <div id="map"></div> <script> // Initialize and add the map function initMap() { var map = new google.maps.Map( document.getElementById('map'), {zoom: 4, center: {'lat': 42.6803769, 'lng': -89.03211}}); {% for Listing in posts %} new google.maps.Marker({position: {'lat': {{ Listing.lat }}, 'lng': {{ Listing.lng }}}, map: map}); {% endfor %} } </script> <!--Load the API from the specified URL * The async attribute allows the browser to render the page while the API loads * The key parameter will contain your own API key (which is not needed for this tutorial) * The callback parameter executes the initMap() function --> <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBvYLD6Huu01-tspszRu-eoCKhWTMnvfXU&callback=initMap"> </script> {% endblock %} I need to make the line: new google.maps.Marker({position: {'lat': {{ Listing.lat }}, 'lng': {{ Listing.lng }}}, map: map}); redirect to /preview/{{ Listing.pk }} when clicked. How can I make my … -
Django_filters multiple arguments for non-model field
I need my endpoint to accept queries in the format: groupId=11111&groupId=22222 and resolve to a query: groupId=1111 OR groupId=2222 I couldn't find anything in the documentation on how to do this, and made the following implementation (currently WIP, haven't written many tests): 2 from django_filters import rest_framework as filters 32 class CustomFilter(filters.UUIDFilter): 33 def filter(self, qs, value): 34 if "groupId" not in self.parent.data: 35 return super().filter(qs, value) 36 37 q = Q() 38 for val in self.parent.data.getlist("groupId"): 39 q |= Q(**{f"{self.field_name}__{self.lookup_expr}": val}) 40 return self.get_method(qs)(q) Used like: 45 groupId = CustomFilter(field_name="group_id", help_text="Jobs associated with group") I have two questions: Is there a way to implement this using what is already in the framework? Is there a way of finding the field name on the request? (groupId instead of group_id)