Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to OneToOneField have many table?
I want to make this. Class Post has ContentId (OneToOneField) Class PostContent has postId (OneToOneField) Class PostContentClub has postId(OneToOneField) both PostContent and PostContentClub are Post. but, the contents are different. So, I want to share them. How do I write the code? -
django-rest-framework- Filtering using 'or' on multiple values from one url parameter
I have a tagging system in place for a model that my API exposes. The models look something like this: class TaggableModel(models.Model): name = models.CharField(max_length=255) tags = models.ManyToManyField(Tag, related_name="taggable_models") class Tag(models.Model): tag = models.CharField(max_length=32) I've then set up a serializer and view that look like: class TaggableModelSerializer(serializers.ModelSerializer): class Meta: model = TaggableModel fields = ('id', 'name', 'tags',) read_only_fields = ('id',) class TaggableModelViewSet(viewsets.ModelViewSet): queryset = TaggableModel.objects.all() serializer_class = TaggableModelSerializer permission_classes = (AllowAny,) filter_backend = [DjangoFilterBackend] filterset_fields = ['tags'] If I want to grab all TaggableModels that have tag ids 1, 2, or 3, I can do so via: https://my-api-domain/api/taggable-models?tags=1&tags=2&tags=3 Is there a way to split on a delimiter, so I can pass it all as one parameter? e.g.: https://my-api-domain/api/taggable-models?tags=1,2,3 It looks like I can write my own custom DjangoFilterBackend filters, but I am a bit unsure as to where to start. Or perhaps there is an easier way to accomplish this? -
search data for table template by django.can't not show next page >
i'm create template for search this table.it can search but click for next page is error in the picture For Error Same mycode. @view.py def search(request): query = request.GET.get('q1') qselect = request.GET.get('q2') qs = Record_data.objects.filter(Q(invoice_no__startswith=query) | Q(product=query)) page = request.GET.get('page', 1) paginator = Paginator(qs, 5) try: page1 = paginator.page(page) except PageNotAnInteger: page1 = paginator.page(1) except EmptyPage: page1 = paginator.page(paginator.num_pages) template_name = 'status.html' context = {'object_list': page1} # page function @html code {% if object_list.has_other_pages %} <ul class="pagination"> {% if object_list.has_previous %} <li class="page-item"><a class="page-link" href="?page={{ object_list.previous_page_number }}">Previous</a></li> {% else %} <li class="page-item disabled"><span class="page-link">Previous</span></li> {% endif %} {% for i in object_list.paginator.page_range %} {% if object_list.number == i %} <li class="page-item active"><span class="page-link">{{ i }}</span></li> {% else %} <li class="page-item"><a class="page-link" href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if object_list.has_next %} <li class="page-item"><a class="page-link" href="?page={{ object_list.next_page_number }}">Next</a></li> {% else %} <li class="page-item disabled"><span class="page-link">Next</span></li> {% endif %} </ul> {% endif %} -
How to make a horizontal navigation bar?
I am trying to make a website with a horizontal navigation bar. I found a useful reference, but I couldn't figure it out to be adopted to my current code since I am not an expert with HTML and CSS. I like to create similar bar like this: ul { list-style-type: none; margin: 0; padding: 0; overflow: hidden; background-color: #333; } li { float: left; } li a { display: block; color: white; text-align: center; padding: 14px 16px; text-decoration: none; } /* Change the link color to #111 (black) on hover */ li a:hover { background-color: #111; } And below are my current code: {% block sidebar %} <ul class="sidebar-nav"> <li><a href="{% url 'index' %">Home</a></li> <li><a href="">All users</a></li> <li><a href="">All productss</a></li> <!-- <li><a href="">All vendors</a></li> --> </ul> {% endblock %} .sidebar-nav { margin-top: 20px; padding: 0; list-style: none; } -
Django Template Not Extending
I'm trying to extend a base template in Django named 'base.html' in my main page 'index.html' and it does not work as expected. Rather than extending the template, the page just displays {% extends 'base.html' %}, plus the HTML in index.html when displaying the index page. The 'base.html' page sits in the root of my templates folder and my 'index.html' page sits in templates/pages. In 'base.html': {% load static %} ...some code... {% block content %} {% endblock %} ...some code... In 'index.html': {% extends 'base.html' %} {% load static %} {% block content %} ...some code... {% endblock %} In views.py: def index(request): return render(request, 'pages/index.html') In settings.py: TEMPLATES = [{'DIRS': [os.path.join(BASE_DIR, 'templates)] Expected Result: Navbar Content Actual Result: {% extends 'base.html' %} {% block content %} Content {% endblock %} -
Pyzipcode city lookup not working properly
Trying to get the city from the zip code, so I installed the pyzipcode package. However, whenever I try to get the city I get the following error. The state, zipcode, lat/long work normally. I've tried numerous zipcodes and none of them seem to pull any city records. from pyzipcode import ZipCodeDatabase zcdb = ZipCodeDatabase() zipc=zcdb['29839'] zipc.city Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'ZipCode' object has no attribute 'city' The documentation for the package uses 'city' as an example. -
Send notifications through DRF
Hello I'm building a RESTfull application using Django Rest Framework. The clients are android application and react application. I need to send a time based notification to users. -
No errors in custom login form
I've created a custom login form with Django, but incorrect logins don't generate form errors. What do I need to do to get errors passed through the form? class CustomUserLoginForm(forms.ModelForm): class Meta: model = User fields = ['email', 'password'] password = forms.CharField(widget=forms.PasswordInput) widgets = { 'password': forms.PasswordInput(), } -
How to load data into Django template using render and filter loaded data using AJAX requests?
I'm loading data into my template using render. The data I'm sending to the template includes objects called course and reviews. Course has an array of instructors, while each review has one instructor. I'm listing out all the instructors associated to a course as a button on the template, and I would like to filter reviews based on which instructor button the user clicks. I'm already sending the data from the server to the template, but I'm thinking I need to use AJAX in this. Any ideas on how to do this and would it be possible to do this without sending another request to the server and utilizing the data that has already been sent to the template? template {% for instructor in course.instructors %} <button class="ui button"> {{ instructor }} </button> {% endfor %} {% if reviews %} {% for review in reviews %} <p>Usefulness: {{ review.usefulness_rating }}</p> <p>Difficulty: {{ review.difficulty_rating }}</p> <p>Instructor: {{ review.instructor_rating }}</p> <p>Comment: {{ review.comment }}</p> <p>Instructor: {{ review.instructor }}</p> <p>Session: {{ review.taken_season }} {{ review.taken_year }</p> How should I implement the AJAX for this? -
Select value from field with type foreignkey
"""I am creating an API (comments) using DRF. And now I'm confused, I need to get an album so that I can completely create my api, but so far all other fields except the album come. album = serializers.CharField (source = 'comments.name_album', read_only = True) does not help. That's all I get in the answer {"album":"","post":"ahsdh","author":"philip","text":"ahsdhah"}""" class AlbumCreateSerializer(serializers.ModelSerializer): album = serializers.CharField(source='comments.name_album', read_only=True) class Meta: model = Comments fields = [ 'album', 'post', 'author', 'text', ] #apiview class AlbumCreateAPIView(CreateAPIView): queryset = Comments.objects.all() serializer_class = AlbumCreateSerializer permission_classes = [IsAuthenticated, IsAdminUser] def post(self, request,pk=None, *args, **kwargs): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): ready_data = serializer.save() return Response(ready_data.data, status=status.HTTP_201_CREATED) return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST) #model class Comments(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE, related_name='comments') post = models.CharField(max_length=100) author = models.ForeignKey(User, on_delete=models.CASCADE) text = models.TextField(max_length=500) publish_date = models.DateTimeField(default=timezone.now()) def __str__(self): return self.text #ajax$ ('#post_form').on('submit', function(event){ event.preventDefault(); $.ajax({ type: 'POST', url: 'http://localhost:8000/api/albums/create/', data: { 'post': $('#post').val(), 'text': $('#text').val(), 'author': $('#author').val(), 'album': $('#album').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success: function(data){ console.log(data); } }); }); #html form <form id="post_form" method="post" action="/api/albums/create/"> <input type="hidden" name="csrfmiddlewaretoken"> <input type="hidden" id="author" value="{{ user }}"> <input type="hidden" id="album" value="{{ comments.name_album }}"> <input type="text" id="post"></br> <input type="text" id="text"></br> <button>submit</button> </form> -
Does django-saml2-auth support share tokens between service providers (SPs)?
First of all, SAML noob here. Does django-saml2-auth support tokens being shared between Service Providers (SPs)? Eg. Service provider A can perform an API request with a SAML token (issued by same IdP) to Service provider B, so the request is authenticated automatically (without needing to redirect the browser to IdP)? Some code is better than no code, but I am not familiar with the plugin so I am just gonna make up some imaginary settings that specified in both service providers: MUTUAL_AGREED_IdP = 'http://idp.example.com' By the way, is this called 'federation'? I read the wiki about SAML federation, it mentions about 2 different IdPs to form a federation, but in my example is just one IdP. -
Celery task is recieved but not executed when using gevent or eventlet (works with prefork)
I'm running celery to send requests to Google Firebase in the background. It works fine when I use prefork. However if I switch to a threading alternative like gevent or eventlet, the tasks do not execute (even though they are received). It seems like celery is unable to connect to the network when I use gevent/eventlet. 9-09-08 21:13:11,629: DEBUG/MainProcess] Task accepted: wallet.realtime.update_balance[783e2791-89ca-42eb-869e-64a04e8bff5b] pid:17399 [2019-09-08 21:13:11,662: DEBUG/MainProcess] Making request: POST https://oauth2.googleapis.com/token [2019-09-08 21:13:11,663: DEBUG/MainProcess] Starting new HTTPS connection (2): oauth2.googleapis.com:443 [2019-09-08 21:13:31,635: ERROR/MainProcess] Task wallet.realtime.update_balance[783e2791-89ca-42eb-869e-64a04e8bff5b] raised unexpected: ServiceUnavailable('Deadline Exceeded') google.api_core.exceptions.ServiceUnavailable: 503 Deadline Exceeded It works perfectly fine with prefork, so shouldn't be a connectivity issue. This is my celery config: celery --app=bosm2019 worker --pool=gevent --concurrency=100 -Ofair --loglevel=DEBUG What should I do? -
how to fix django staticfiles page not found in heroku?
static files are not working in production in Heroku.but when in development it works, since yesterday I couldn't solve it. please help me. settings.py STATIC_ROOT=os.path.join(BASE_DIR,'staticfiles') STATIC_URL = '/static/' MEDIA_URL='/media/' MEDIA_ROOT=os.path.join(BASE_DIR,'media') CRISPY_TEMPLATE_PACK='uni_form' LOGIN_URL='/login' LOGIN_REDIRECT_URL='/app' LOGOUT_REDIRECT='/' -
Passing variable from javascript to django views
Iam creating simple "rock paper scissors" game with some css animations and so on, where most of the stuff happens in javascript, as learning JS is what Iam focusing on mostly at the moment. User vs computer match also happens in javascript. When match is finished Iam assigning users earned exp(points) to new variable. What Iam trying to do now is sending that data(earned exp) to the views, so i can save it back in db(users.exp). I think jqery ajax or fetch api should do that if Iam right but after hours of trying I probably just dont get it. Any1 can give me some tips, explenation? not just solution please. Views: @login_required def profile(request): if request.user.is_authenticated: user = request.user userObj = Profile.objects.filter(user=user) usersLevel = userObj[0].level usersPoints = userObj[0].points context = { 'usersLevel': usersLevel, 'usersPoints': usersPoints, } return render(request, 'rps_app/game.html', context) else: print('No user logged in!') return render(request, 'rps_app/game.html') This is my template where Iam loading users data: <script type="text/javascript"> var usersLevel = '{{usersLevel|safe}}'; var usersPoints = '{{usersPoints|safe}}'; </script> js: let users_level = Number(usersLevel); let users_points = Number(usersPoints); progressbar.style.width = `${users_points}%`; ... -
In Python, is it possible to mock requests inside another request?
In Django, I have a view which makes a request to an external API. The view is in my_app. class ExternalAPIView(View): def get(self, request, *args, **kwargs): ... external_api_response = requests.get(settings.EXTERNAL_API_URL) ... For its unit tests, I use the following function for the side_effect parameter of the @patch decorator. def mocked_requests_get_for_external_api(*args, **kwargs): class MockResponse: def __init__(self, content, status_code): self.content = content self.status_code = status_code if args[0] == settings.EXTERNAL_API_URL: return MockResponse(json.dumps('{"value": 1}'), 200) return MockResponse(None, 404) ... and the unit test goes like this without an issue: @patch("my_app.views.requests.get", side_effect= mocked_requests_get_for_external_api) def test_external_api(self, mock_get): response = self.client.get(settings.EXTERNAL_API_VIEW_URL) assert response.status_code == 200 data = json.loads(response.content) assert data["value"] == 1 However, I have another view in the same project, which calls this ExternalAPIView as follows: class MainView(View): def get(self, request, *args, **kwargs): ... response = requests.get(request.build_absolute_uri(settings.EXTERNAL_API_VIEW_URL)) ... I'd like to create a unit test for this MainView, which will make the call to the ExternalAPIView through settings.EXTERNAL_API_VIEW_URL, but mock external API call inside the ExternalAPIView. Is it possible at the first place? And if so, how can I do that? -
Django request.user become AnonymousUser after third party redirect
test.html: <a href="https://auth.ebay.com/oauth2/authorize? ...">authorize</a> views.py: from django.contrib.auth.decorators import login_required @login_required def myview(req): user = req.user return render(req, 'test.html') For ebay's oauth process, you have to provide users with a link to ebay's server, which asks the user if they want to give credentials to you. If they accept, ebay redirects the user to a given url with a querystring containing the access key. The problem is, when I authorize my app with ebay, the user gets redirected to my login page (despite already being logged in). If I remove the @login_required decorator, req.user returns AnonymousUser instead. This is a problem since I don't know which user to assign the access token to. What am I missing here? Note that I am using ngrok to tunnel my server, and I have no problems rendering myview other than the fact that the user is Anonymous. -
Django: dynamic choice field for formsets
So I have a form class DownloadForm(forms.Form): title = forms.CharField() device_family = forms.ChoiceField(label="Device Family", widget=forms.Select(attrs={'class': 'form-control', 'data-toggle': 'select'}), choices=LOG_ENTRY_TYPES, required=True ) and in view.py I do LOG_ENTRY_TYPES = ( ('', 'All'), ('auth', 'Auth'), ('error', 'Error'), ('info', 'Info'), ('proxy', 'Proxy'), ) DownloadFormSet = formset_factory(DownloadForm) formsets = DownloadFormSet(initial=[ {'title': 'Django is now open source', 'device_family': LOG_ENTRY_TYPES}, {'title': 'Django source 2', 'device_family': LOG_ENTRY_TYPES}, {'title': 'Django source 3', 'device_family': LOG_ENTRY_TYPES} ]) This creates the device_family field but the LOG_ENTRY_TYPES choices are not generated. So how can I pass the LOG_ENTRY_TYPES choices to the device_family choices field so that the drop down shows the choices. -
How to put a breakpoint on django-rest-framework package in vscode to debug?
I want to put a breakpoint on Create method of serializer.py located in Django-Rest-Framework in visual studio code but i am shown unverified breakpoint. Is there a way to go deep into extrnal libraries in vscode ? My breakpoint changes to a gray breakpoint when i want to debug extrnal libraries like below. -
Prefetching unrelated model on arbitrary field equivalence
I have a code like this: for m in MyModel.objects.filter(...): mo = MyOtherModel.objects.get(myOtherField=m.myField) print("{:s}{:s}".format(m, mo)) This is inefficient because finding mo requires a new query to the database. To avoid this I was thinking to use either prefetch_related(Prefetch()) or .annotate(). The problem with the first is that Prefetch() would need a foreignkey relationship between the 2 models (they have none). Same thing .annotate: MyModel.objects.filter(...).annotate(moWithSameField=F('myField') == F(???)) ^ This would be also be wrong even if I knew what to write in ???. Is this possible to do? Can you prefetch something completely unrelated based on an arbitrary query? -
Auto_now_add = true fields don't appear in the admin section because they are not editable - can you make them appear though?
As the title says, the fields with auto_now and auto_now_add don't appear in the admin section, acoording to this: Django auto_now and auto_now_add Can you somehow make them appear though? It doesn't matter if they are not editable, I just want them there so I can see the whole entry. Or is there any similar function which would set the date to the current time but would make it editable? That would be okay too, because the date will appear in the admin panel. Thanks. -
How to collect information from nav tab and submit as single form
I am using NAV to collect information from user, instead of one single view, so thought to divide up into nav tab and at the end get all the data and submit. I'm using Django, with Model with define fields, View is get valid POST. Here is the HTML looks like: <div align="center" class="container"> <form id="collectINFO" role=form method="POST" class="nav nav-pills post-form" action="{% url 'collectINFO' %}">{% csrf_token %} <ul align="center" class="nav nav-pills nav-pills-rose"> <li class="nav-item"><a class="nav-link active" href="#pill1" data-toggle="tab">TAB1</a></li> <li class="nav-item"><a class="nav-link" href="#pill2" data-toggle="tab">TAB2</a></li> </ul> <div class="tab-content tab-space"> <div align="center"class="tab-pane active" id="pill1"> <br><br> <input name="input1" id="input1" class="form-control" type="text" maxlength="20" required /> <input name="input2" id="input2" class="form-control" type="text" maxlength="2" required /> </div> <!-- end of pill-1 --> <div class="tab-pane" id="pill2"> <div class="row"><div class="col"> <input id="data1" class="form-control" rows="1" type="text" name="hostname" maxlength="20" required></input> </div></div> <!-- end of pill-2 --> </div> <div align="center" class="container"> <div id="submit" class="row"> <div class=" col"> <button type="submit" class="btn btn-primary btn-lg">SAVE</button> </form></div> When I hit SAVE nothing happens no log also in the VIEW I have added print(form.error) and print(form) here is the VIEW looks like def CollectINFO(request, *args, **kwargs): template_name = 'CollectINFO.html' if request.method == 'POST': form = CollectINFO_Form(request.POST or None) print(form.is_valid()) print(form.error) if form.is_valid(): task = form.save() messages.success(request, 'SUCCESSFULLY!!!') else: … -
How to filter deeper in objects in django?
I want to filter on the fruit type in my django project. The problem is that I use many objects and the last one needs to get filtert. Here is an example of the structure. So I would like that my inputs only show the plots that are manytomany that have the fruit pear for example. I tried the following code to see what path I had to get to the fruit: Input.objects.get(pk=1).plot.get(pk=1).Fruittype.fruit this returns: <Fruit: pear> So this is the correct path but I don't know how i can filter all the objects to the fruit. Sorry if it is unclear what I mean, but this is not my native language. -
Prefetching manytomany field doesn't change execution speed
m = MyModel.objects.all().only("colA", "colB").prefetch_related("manyToManyField") for mm in m: print(mm.id) list(mm.manyToManyField.values_list('id', flat=True)) This code takes too long to execute. This takes virtually no time (no reference to manyToManyField in loop): m = MyModel.objects.all().only("colA", "colB").prefetch_related("manyToManyField") for mm in m: print(mm.id) And this takes nearly the exact same time as the first m = MyModel.objects.all().only("colA", "colB") for mm in m: print(mm.id) list(mm.manyToManyField.values_list('id', flat=True)) This makes me think that .prefetch_related("manyToManyField") is useless and it is not actually fetching anything and list(mm.manyToManyField.values_list('id', flat=True)) hits the database for every cycle. Why is this and how can I force to prefetch from a manytomany field? -
Form without submit button - Django
I see that forms without buttons are very popular (like here). How to create a form that will be automatically submit for two different fields in Django, after the user selects the field (example 1) or type in the text and clicks something (it means completes typing) (example 2): 1.) ChoiceField forms.py class Search(forms.Form): field = forms.ChoiceField(choices=MY_CHOICES) views.py if request.method == "GET": form = Search(request.GET) if form.is_valid(): print('it's work') template.html <form method="GET"> {% csrf_token %} {{ form }} </form> 2.) CharField forms.py class Search(forms.Form): field = forms.CharField(max_length=10) * other files like above Any help will be appreciated -
how to keep rows order from a pandas dataframe to a dict
i have a pandas dataframe which is already sorted by date, but i need to serialize this dataframe to a dict python structure keeping the rows order so i can later return a JSON. i use a dict where i have some keys and values and i need the dataframe to be a value. i used pd.to_dict() but this dont keep the rows order i've tried to use OrderedDict but i can't serialize this with json.dumps(). I'm using python 2.7 dic_data = { 'data':data.to_dict(), 'variable':variables[variable], 'unit':units[variable], 'limits':{ 'limite_superior':lim_sup, 'limite_inferior':lim_inf } } return HttpResponse(json.dumps(dic_data),content_type="application/json") this is the datraframe data that im trying to convert into rows ordered dict to later serialize it in json date_time values 202 2018-09-01 10:00 0,9 203 2018-09-01 11:00 0,1 204 2018-09-01 12:00 0,0 205 2018-09-01 13:00 0,0 206 2018-09-01 14:00 0,0 207 2018-09-01 15:00 0,0 208 2018-09-01 16:00 0,0 209 2018-09-01 17:00 0,0 the json object that im receving from de data dataframe has the following structure: { date_time:{ 0:"2018-09-01 20:00", 1:"2018-09-01 21:00", .... }, values:{ 0:20.54, 1:30.45, ..... } } and actually i need the same structure but with rows ordered pd: sorry for my bad english