Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 1.10 Delete large cascade querySet
I'm trying to delete all objects from a large queryset. Here is my models.py from __future__ import unicode_literals from django.contrib.auth.models import User from django.db import models class Fund(models.Model): name = models.CharField(max_length=255, blank=False, null=False) start_date = models.DateField(default=None, blank=False, null=False) def __unicode__(self): return self.name class FundData(models.Model): fund = models.ForeignKey(Fund, on_delete=models.CASCADE) date = models.DateField(default=None, blank=False, null=False) value = models.FloatField(default=None, blank=True, null=True) def __unicode__(self): return "{} --- Data: {} --- Value: {} ".format(str(self.fund), str(self.date), str(self.value)) But when I try to delete all records the query take too much time and mysql is being timed out. Fund.objects.all().delete() What is the best way to manage this operation inside a view? There is a way to do that calling a django command from terminal? -
Any limitation on HTML <li>?
I have the following code with Python: <div id="sidebar-wrapper" class="container-fluid" style="background-color: lightgray"> <nav id="spy" class="nav nav-pills navbar-stacked"> <ul class="sidebar-nav nav"> <li class=""> <a href="{% url 'PHIproduct' %}" data-scroll="" class=""> <span class="fa fa-anchor solo"><h3>Product List</h3></span> </a> <li class=""> {% for i in loop_times_product %} <a href="{% url 'PHI' %}?id={{ i }}" data-scroll="" class=""> <span class="fa fa-anchor solo" id="{{ i }}">{{ i|safe }}</span> </a> {% endfor %} <li class=""> {% for i in loop_times %} <a href="{% url 'PHIc' %}?id={{ i }}" data-scroll="" class=""> <span class="fa fa-anchor solo" id="{{ i }}">{{i|safe}}</span> </a> {% endfor %} <li class=""> {% for i in loop_timesc %} <a href="{% url 'button' %}?id={{ i }}" data-scroll="" class=""> <span class="fa fa-anchor solo" id="{{ i }}">{i|safe}}</span> </a> {% endfor %} </li> </li> </li> </li> </ul> </nav> </div> The main purpose is to add following feature: After I apply this code, when product A is clicked, the car and motor will not show, which means this part of code is not running: <li class=""> {% for i in loop_timesc %}<a href="{% url 'button' %}?id={{ i }}" data-scroll="" class=""><span class="fa fa-anchor solo" id="{{ i }}">{{i|safe}}</span></a> {% endfor %} </li> Is there any limitation on li code or am I writing the … -
ValidationError HTTP Code for 'user already exist'
I'm doing a login app for my Django project using Django Rest Framework. At registration, in my serializer, i'm checking if user already exist by doing this: def create(self, validated_data): """ Create an user but validate datafirst(checking if exist, if mail is right,not already in-use, and hash password). """ queryset = PictureUser.objects.filter(username=validated_data['username']) try: queryset[0] raise serializers.ValidationError('The username is already used.') except IndexError: print ("User don't exist.") user = PictureUser.objects.create( email = validated_data['email'], username = validated_data['username'], password = make_password(validated_data['password']), ) user.save() return user This work pretty well. But the HTTP code sent is 400 when the user already exist. How can I change it to 409 or 422 to be more accurate on what went wrong ? (400 error would imply many other errors.) Must I return an HttpResponse instead? Thanks. -
Usage of " If not x: do something " in Django/Python
I found a very useful answer for this question below, but it is a bit unclear to me. Why is "if not someobj:" better than "if someobj == None:" in Python? From my understanding of how " if not x: do something " works is that "if not" just checks to see if the value of x is True or not. If it isn't, it will do something. I am learning Django and in one of the examples I am trying to understand, they use the "if not:" logic to set up a shopping cart. Here is how the code is written by someone much smarter than I am: in settings.py file: CART_SESSION_ID = 'cart' in cart.py file: from django.conf import settings class Cart(object): def __init__(self, request): """ Initialize the cart. """ self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: # save an empty cart in the session cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart So it seems to me like CART_SESSION_ID is a string initially with the value 'cart'. The variable cart must be a dictionary to store product ids, price and quantity. Since the initial value of "cart" is a string with a value, would "if … -
how to compare two querysets in django templating?
This might sound super similar to other postings about comparing two querysets using zip and other choices but I have been reading lots and none of them gave me a good idea what I can do for the comparing I need. To start off, I am getting queries from db and in the html templating I need to generate some defaults for select element. With one default is easy but with multiple I am having trouble since there's no break in django templating. let's say I have these two querysets that I get returned from backend [<J: j1>, <J: j2>, <J: j3>, <J: j4>] [<J: j2>, <J: j4>] I tried something like this to start with and I can understand that it's looping more than needed so I am getting more outputs than needed too. I tried searching for something that would break the loop but figured there's no breaking up the loop in django template <select name="" id=""> {% for j in all_j %} {% for s in all_s %} {% if j.id == s.id %} <option value="{{ j.id }}" selected="selected">{{ j.name }}</option> {% else %} <option value="{{ j.id }}">{{ j.name }}</option> {% endif %} {% endfor %} {% … -
Where to host a medium-sized web app in Vue.js and Django?
I'm building a web app and I would like to host it online but I am completely new to this. I made some research and found out that I have a bunch of different, as well as confusing, options: Professional hosting service Dedicated server (too expensive right now) Virtual private server Cloud services (e.g. Google Cloud Platform) What I need is a reliable and scalable place to host my app. Something that is free or cheap at first (50€/month maximum) but I should also be able to upgrade it as soon as the number of users start growing. Provided that I use: Vue.js for frontend Django for backend PostgreSQL as DBMS Is the Google App Engine a good option for me? How much would it cost per month? I tried using Google Cloud Platform pricing calculator but I need a lot of information of which I'm totally ignorant (e.g. istances per hour or number of cores per hour) If you think that Google App Engine isn't good for what I need what are your suggestions? Thanks in advance -
uploading file and title using query parameters
I am using Django RestFramework. I would like to if it is possible to upload a file and title using url parameter. For example, http://127.0.0.1:8000/upload/title='some-title'&file_url='some-path' Can anyone please guide as i am beginner in django rest framework.Here is my code: Model: class MyModel(models.Model): title = models.TextField(max_length=100, blank=True, default='No title', unique=True) file_url = models.FileField(upload_to='files/') created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('created_at',) Serializers: class MySerializer(serializers.ModelSerializer): file_url = serializers.FileField(max_length=None, required=True) class Meta: model = MyModel fields = ('id', 'title', 'file_url', 'created_at') Views: class MyViewSet(ModelViewSet): queryset = MyModel.objects.all() serializer_class = MySerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) class MyAPIView(generics.CreateAPIView): serializer_class = MySerializer permission_classes = (permissions.IsAdminUser,) def get_queryset(self): title = self.lookup_field['title'] file_path = self.lookup_field['file'] obj = MyModel.objects.create(title=title, file_url=file_path) serializer = MySerializer(obj) return Response(serializer.data) Urls: router = DefaultRouter() router.register(r'django', MyViewSet) urlpatterns = [ url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^upload/(>P<title>[\w+])&?P(<file>[\w+])/$', MyAPIView.as_view()), url(r'^', include(router.urls)) ] -
Why form is not valid in django
Why form is not valid in django! hi i dont know why my form is not valid! i tried this class SignupForm(forms.Form): first_name = forms.CharField(required=True, max_length=35) last_name = forms.CharField(required=True, max_length=35) username = forms.CharField(required=True, max_length=50) email = forms.EmailField(required=True) password = forms.CharField(required=True, min_length=8, max_length=64) confirm_password = forms.CharField(required=True, min_length=8, max_length=64) template.html <form id="signupForm" action="" method="POST" accept-charset="utf-8" class="form" role="form">{% csrf_token %}<div class="row"><div class="col-xs-6 col-md-6"><input id="first_name" type="text" autocomplete="off" name="firstname" value="" class="form-control input-lg " placeholder="First Name" /></div><div class="col-xs-6 col-md-6"><input id="last_name" type="text" autocomplete="off" name="lastname" value="" class="form-control input-lg " placeholder="Last Name" /></div></div><input id="username" type="text" autocomplete="off" name="username" value="" class="form-control input-lg " placeholder="Choose Username" /><input id="email" type="text" autocomplete="off" name="email" value="" class="form-control input-lg " placeholder="Your Email" /><input id="password" type="password" autocomplete="off" name="password" value="" class="form-control input-lg " placeholder="Password" /><input id="confirm_password" type="password" name="confirm_password" value="" class="form-control input-lg " placeholder="Confirm Password" /><div class="topmargin active"><div class="row" style="display: flex;"><div class="col-xs-5 col-md-5"><label>I'm </label><select name="month" class = "form-control input-lg "><option value="male">Male</option><option value="female">Female</option></select></div><br /><span class="help-block">By clicking Create my account, you agree to our Terms and that you have read our Data Use Policy, including our Cookie Use.</span> Create my account i think it's because i dont pass the form to template, but i dont wanna do that! it mixes the responsive style commands are welcome thank you -
Passing the same context variable to multiple function views
Is there any efficient way to pass the same context to multiple views? This is what I mean: def first(request) form = SomeForm(request.POST or None) return render(request, 'base.html', {'form': form}) def home(request) form = SomeForm(request.POST or None) return render(request, 'homepage.html', {'form': form}) def profile(request) form = SomeForm(request.POST or None) return render(request, 'profile.html', {'form': form}) As you can see I'm passing the same context to multiple views. It's a context I have to pass to basically every view as it's a uniform variable I need throughout the website. Is there any way to make this more efficient? -
How to configure Django Rest Framework + React
I have an application backend in Django-rest-framework, and I have a reactjs app. How can I do to they work together ? For development I open 2 terminals and run them separately. There is some way to make them work together ? Also to deploy it to production I have no idea how I can do that. I tried to look for some github project ready, but couldn't find anything Thanks! -
Delete model with cascade error
I trying to delete 1 foreign key in my model and two foreign key of my foreign key before. Credit Card Model: - FK: Customer Customer Model: - FK: Address (null true, blank true, on_delete=cascade) - FK: Phone (null true, blank true, on_delete=cascade) I trying this: credit_card.customer.address.delete() credit_card.customer.phone.delete() credit_card.customer.delete() credit_card.delete() And I getting this: (1048, "Column 'address_id' cannot be null") -
How to serialize(JSON) FileField in Django
I am new to Django and trying to build an app to test out few things for my project. I want to read the form - do some validation and then send the input to another module (say a scheduler running separately). The scheduler rest api will be called with the form data (which is file) and the scheduler will load the data into the models. I am using python requests and serializing data into json before calling the rest api. This is where I am getting error. Django on request.FILES create a InMemoryUploadedFile class which has the data loaded somewhere in memory and serializing this to Json is not straightforward. I tried looking other ways (like image serializers example) but not able to resolve this issue. forms.py class UploadDatasetForm(forms.Form): docfile = forms.FileField(label='Choose file') views.py def test_upload(request): if request.method == 'POST': form = UploadDatasetForm(request.POST, request.FILES) if form.is_valid(): in_file = request.FILES['docfile'] payload = {'doc_file': in_file} msg = json.dumps(payload) URL = 'http://localhost:8880/form' r = requests.post(URL, data=msg) return HttpResponse(json.dumps(r.text), content_type="application/json") Error: raise TypeError(repr(o) + " is not JSON serializable") TypeError: <InMemoryUploadedFile: A_test.csv (text/csv)> is not JSON serializable Any help here will be appreciated. Thanks a lot. -
Extending an inherited model from a different django application
I created an additional application with Django and I am trying to inherit a model from a different application, which will have some additional fields, but should have the same instances in the admin interface. For example if I create an instance in application1 called test, I should be able to see it in the admin interface of both applications and also be capable of giving it the number 1 in application2 and vice versa - create test with the number 1 in application 2 and be able to see it in both admin interfaces. The only difference is that the number has to be visible only in application2. So I have something like this: #app1 class Model1(models.Model): name = models.CharField(max_length=100) #app2 from app1.models import Model1 class Model2(Model1): number = models.IntegerField(unique=True) So far, so good. This works almost as wanted. The only problem is, that in the admin interface, the child model (Model2 from application2) has no vision of the instances created in Model1. I have also read about abstract classes and proxy classes, however, I do not think, that that is what I am looking for, because with abstract classes it is not possible to register the model in … -
Django "Manager isn't accessible via UserProfile instances"
Here is my views.py if request.user.is_authenticated(): changepass = request.user.userprofile.objects.get(user=request.user) if changepass.force_password_change == True: changepass.force_password_change = False changepass.save() return HttpResponseRedirect('/login/register/') elif changepass.force_password_change == False: return HttpResponseRedirect('/main/') This line changepass = request.user.userprofile.objects.get(user=request.user) is the problem according to Django. I am trying to access force_password_change from UserProfile. As the title suggests, I am getting the error Manager isn't accessible via UserProfile instances. Here is my models.py for reference. class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) force_password_change = models.BooleanField(default=True) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) post_save.connect(create_user_profile, sender=User) -
Django display model related to other models in table
First of all, excuse my English, I'm new in Django, and really eager to learn. I've been doing things for one year with Python. That's all my experience. I'm trying to make a table with a list of articles listed in a column of the table, and in the other columns there is the name of some sellers at the top, then the price of the articles is listed in each sellers column with their respective price of that article. I have this code in models.py class Item(models.Model): name = models.CharField(max_length=200) class Seller(models.Model): name = models.CharField(max_length=200) class Price(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) seller = models.ForeignKey(Seller, on_delete=models.CASCADE) price = models.CharField(max_length=10) This is my views.py def index(request): all_items = Item.objects.all() sellers = Seller.objects.all() prices = Price.objects.all() return render(request, 'juegos/index.html', {'all_items': all_items, 'sellers': sellers, 'prices': prices} ) In the template i have this: <thead> <tr> <th>Item</th> {% for seller in sellers %} <th>{{ seller.name }}</th> {% endfor %} </tr> </thead> <tbody> {% for item in all_items %} <tr> <td>{{ item.name }}</td> <!--I don't know how to list each price for each seller--> {% endfor %} </tr> </tbody> </table> When i add prices in the admin, i just choose item from a previous added … -
Running spider from crawl command and from CrawlerProcess does not output the same
I implemented a scrapy spider that I used to call using scrapy crawl myspider -a start_url='http://www.google.com' Now I need to run that spider from a script (from a django app, using django-rq but that shouldn't have any impact for the question). Thus, I followed the CrawlerProcess doc to end up with a script like this crawler_settings = Settings() crawler_settings.setmodule(cotextractor_settings) process = CrawlerProcess(settings=crawler_settings) process.crawl(MySpider(start_url='http://www.google.com')) process.start() Issue is that, from the script, my crawl fails due to a missing start_url arg. After digging into both spiders output, I noticed that the second one (from the script) was displaying twice a debug command I've set up in my spider constructor. Here is the constructor def __init__(self, *args, **kwargs): super(MySpider, self).__init__(*args, **kwargs) logger.debug(kwargs) self.start_urls = [kwargs.get('start_url')] Here is the crawl command output; notice there is only 1 debug output 2017-07-11 21:53:12 [scrapy.utils.log] INFO: Scrapy 1.4.0 started (bot: cotextractor) 2017-07-11 21:53:12 [scrapy.utils.log] INFO: Overridden settings: {'BOT_NAME': 'cotextractor', 'DUPEFILTER_CLASS': 'cotextractor.dupefilters.PersistentDupeFilter', 'NEWSPIDER_MODULE': 'cotextractor.spiders', 'SPIDER_MODULES': ['cotextractor.spiders'], 'USER_AGENT': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36'} 2017-07-11 21:53:12 [scrapy.middleware] INFO: Enabled extensions: ['scrapy.extensions.corestats.CoreStats', 'scrapy.extensions.telnet.TelnetConsole', 'scrapy.extensions.memusage.MemoryUsage', 'scrapy.extensions.logstats.LogStats'] 2017-07-11 21:53:12 [cotextractor.spiders.spiders] DEBUG: {'start_url': 'http://www.google.com'} 2017-07-11 21:53:13 [scrapy.middleware] INFO: Enabled downloader middlewares: ['scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware', 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware', 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware', 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware', 'scrapy.downloadermiddlewares.retry.RetryMiddleware', 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware', 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware', 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware', … -
Custom Manager in Django Destroys Caching for prefetch_related
If I do everything below without a custom manager, it all works as expected: class Content(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Meta: app_label = 'game' class Requirement(models.Model): content = models.ForeignKey(Content, on_delete=models.CASCADE, related_name = 'requirements') value = models.IntegerField(default=0) def __str__(self): return "{} requires value {}".format(self.content,self.value) class Meta: app_label = 'game' def testPrefetchOrig(): contents = Content.objects.filter(name__startswith = 'a').prefetch_related('requirements') for c in contents: for r in c.requirements.all(): print r logging.warning(r) logging.warning("Done with query") This prefetches the data once and never again: DEBUG:django.db.backends:(0.001) SELECT "game_content"."id", "game_content"."name", "game_content"."deleted" FROM "game_content" WHERE "game_content"."name"::text LIKE 'a%'; args=(u'a%',) DEBUG:django.db.backends:(0.001) SELECT "game_requirement"."id", "game_requirement"."content_id", "game_requirement"."value", "game_requirement"."deleted" FROM "game_requirement" WHERE "game_requirement"."content_id" IN (5, 6); args=(5, 6) alphabet requires value 5 WARNING:root:alphabet requires value 5 alphabet requires value 3 WARNING:root:alphabet requires value 3 albatross requires value 1 WARNING:root:albatross requires value 1 albatross requires value 0 WARNING:root:albatross requires value 0 WARNING:root:Done with query However, I want to use a custom manager to handle filtering of entries that are 'deleted' by setting a deleted flag. class DeletedItemsQuerySet(models.query.QuerySet): def get(self, *args, **kwargs): kwargs['deleted']=False return models.query.QuerySet.get(self, *args, **kwargs) def all(self): return self.filterNoDeleted() def filterNoDeleted(self, *args, **kwargs): kwargs['deleted']=False return models.query.QuerySet.filter(self, *args, **kwargs) def getDeleted(self, *args, **kwargs): return models.query.QuerySet.get(self, *args, **kwargs) def filterDeleted(self, *args, **kwargs): … -
Get normalized form data from BoundField in django template
I have a ModelForm with some IntegerFields and DecimalFields, and I need to render them on server using current locale format for view, and using regular format for JS interop. Currently I'm using form.currency.value|default:1|stringformat:"d" for integers and form.rate.value|default:0|stringformat:"f" for decimals. But since that's form, when there's bound data in form, form.rate.value is string, and stringformat returns empty string. Is it possible to access normalized data from template? If yes - how? If no - how should I handle both cases? Handling this in view for each and every field seems like an overkill, but handling types in template seems no better. Best way I can think of is to register custom filter, handle types there, return string with number literal. -
Capture all the state change messages Celery Django
I have a celery task on a remote server and i am executing it with from another server using django. Below is the celery task conf. from celery import Celery from celery import current_task app = Celery('project', backend='redis://localhost:6379/0', broker='redis://localhost:6379/0') I am sending the task using app.send_task('task_name', args) . The task updates its state using current_task.update_state('SOMETHING') Now i want to capture all messages and states from the remote task. I can receive results using task_obj = AsyncResult(task_id) task_obj.get(on_message=on_msg) def on_msg(body): # do something here task_obj.get is a blocking call and waits until it gets result. I want to know if there is a way to handle this situation using celery. Obviously I can run a python daemon for keep running task_obj.get until it finishes but i want to know if there is a better way to do it -
How can I limit the number of objects created per hour in Django?
The question is quite specific, is there any way to limit the user so that he can only create a number of objects per hour? I'm creating a social network and I need to be able to moderate spam. -
Django Migration: prevent base model creation after abstract inheritance
I am creating a BaseModel and inheriting it in Channel.This BaseModel would have more logic while performing save(). I am facing an issue while migrations are completed and tables are generated. My api_channel table is created with basemodel_ptr_id referencing to BaseModel table. But, what I am looking for is to have all the fields from the BaseModel would be inherited into the Channel model. I also do not need basemodel table in my database. I have gone through the official Django Doc Please help. BaseModel.py from django.db import models from django.utils import timezone class BaseModel(models.Model): created_on = models.DateTimeField(editable=False) updated_on = models.DateTimeField() # # To make the BaseModel abstract class Meta: proxy = True def __init__(self, *args, **kwargs): self._meta.db_table = self.__class_.__name__.lower() super(BaseModel, self).__init__(*args, **kwargs) def save(self, *args, **kwargs): ''' On save, update_at timestamp ''' if not self.id: self.created_on = timezone.now() self.updated_on = timezone.now() return super(User, self).save(*args, **kwargs) Channel.py from django.db import models from api.models import base class Channel(base.BaseModel): name = models.CharField(max_length=50) description = models.CharField(max_length=1000) -
Django Boolean Field used in view.py
I am trying to add a feature to where a new user needs to update his/her password on an initial login. I added a hidden BooleanField to my Profile model where default = True. models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) force_password_change = models.BooleanField(default=True) However, when trying to use force_password_change in my views.py, it never returns the correct value that I set in django's admin page. views.py if request.method == 'POST': ... user = authenticate(request, username=username, password=password) changepass = UserProfile.objects.get(user=request.user) if user: if changepass.force_password_change == True: changepass.force_password_change = False changepass.save() return HttpResponseRedirect('/login/register/') elif changepass.force_password_change == False: if user.is_active: login(request, user) return HttpResponseRedirect('/main/') else: return HttpResponse("Your account has been disabled.") It is currently giving me this error DoesNotExist at /login/ UserProfile matching query does not exist. Request Method: POST Request URL: http://127.0.0.1:8000/login/ Django Version: 1.11.2 Exception Type: DoesNotExist Exception Value: UserProfile matching query does not exist. Exception Location: C:\Python34\lib\site-packages\django\db\models\query.py in get, line 380 Python Executable: C:\Python34\python.exe Python Version: 3.4.4 -
Django: Add and Subtract from inventory in models
I'm trying to do something that I thought would be simple, but it has proven a bit challenging for me right now. I am trying to build a simple ATM system for Banknotes in Django 1.11 and Python 3.6. I basically need to keep track of banknotes that are in stock and how many of each kind. But I realized that using the logic that I'm accustomed with I only create new instances of the model instead of adding to the quantity fields. I know how to use a quantity field to add items of an order (but thats also creating a new instance of an order), but how can I do it to make changes to an inventory without creating a new instance of it? I guess it should have something to do with ManyToManyField and the through argument. I'm also not sure if I should separate each Banknote as one Class or put them all under a single Class. Any ideas? Here's my model: class Cedula(models.Model): um = models.IntegerField(blank=False, default=0) dois = models.IntegerField(blank=False, default=0) cinco = models.IntegerField(blank=False, default=0) dez = models.IntegerField(blank=False, default=0) vinte = models.IntegerField(blank=False, default=0) cinquenta = models.IntegerField(blank=False, default=0) cem = models.IntegerField(blank=False, default=0) class Meta: verbose_name = … -
Django Form Field for Copying and Pasting Vertical List
I am in the process of updating a project so that, in one of the apps, the user can copy a vertical list of values from a text/excel file/[file format] into a form. I want the form to hold as many values as the user will paste (so hopefully it will be dynamic in length). When the user submits the form, my views.py will process the data. What field type should I use to do this? (If it is even possible to do this) -
How to make retrofit request to django api with authentication token?
I am using retrofit from an android app as a means of communicating with a django rest api backend. I have implemented TokenAuthentication and want to make a request to a view which requires users to be authenticated to load all the users. Here is the retrofit interface exposing the /users/ api endpoint: @GET("users/") Call<List<User>> loadAllUsers(@Header("token") Token token); Here is the token model class: public class Token { private String token; public Token() { } public Token(String token) { this.token = token; } public String getToken() { return token; } } Here is the method in the user repository responsible for loading all users (or at least the first 20): @Override public void loadAllUsers(Token token) { Call<List<User>> call = userServiceApi.loadAllUsers(token); call.enqueue(new Callback<List<User>>() { @Override public void onResponse(@NonNull Call<List<User>> call, @NonNull Response<List<User>> response) { if (response.isSuccessful()) { List<User> users = response.body(); eventBus.post(new LoadAllUsersEvent(users)); } else { eventBus.post(new FailLoadAllUsersEvent()); Log.d(TAG, response.message()); } } @Override public void onFailure(@NonNull Call<List<User>> call, @NonNull Throwable t) { eventBus.post(new LoadUsersUnreachableServerEvent()); Log.d(TAG, t.toString()); } }); } Here is the view on the django rest api backend: class UserList(generics.ListAPIView): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (IsAuthenticated,) pagination_class = StandardResultsSetPagination Here is the serializer for that view: class …