Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
search with 2 field in generic api view
Do you know how can I search with 2 fields with 'and' conditions? I mean in the below code I need to search'search_fields' with symbol name and time_frame,(both conditions together not only one of them) class RegisterSymbolViewSet(mixins.ListModelMixin, viewsets.GenericViewSet): serializer_class = SymbolValidationSerializer filter_backends = [filters.SearchFilter] search_fields = ['^symbol','^time_frame'] queryset = RegisterSymbol.objects.all() -
the server responded with a status of 503 (Service Unavailable)
I've built a django application for about 5 months ago, it works fine till yesterday, but now it sometimes shows this error message: The server is temporarily unable to service your request due to maintenance downtime or capacity problems. Please try again later. server: ubuntu version: 18 LTS server provider linode Thank you for any help -
Can't login into admin URL on production with Django 4
Can't seem to login into Django admin URL on my production but it works fine on my local. For context, currently my site does not have SSL. Debug is set to False as well. This was working prior to Django 4 upgrade (was previously on Django 3.08) mysite.com/admin keeps redirecting to mysite.com/admin/login/?next=/admin/ with a 500 error. -
Django ModelMultipleChoiceField
I'm newbie in Django and making my first real application. I need some advice in building page with three dependent model multiple choices fields or another similar interface. The goal is to build a page where user can choice target folders from three-level folders structure and save user selection in DB for further use. I want to crate three list contains L1, L2 and L3 dirs names each, where user selects any available dirs. If user changes selection on L1 dirs list it need to automatically update L2 dirs list, the same rule in L2 dirs list for L3 dirs list. Due to security restrictions I can't access filesystem with dirs from Django server. But it can be accessed from user PC. I guessed to manually load dirs structure, because it is rarely changes. The question is how to embed those lists at page and make them dependent. I guess it must be three model multiple choices fields with some JavaScript event to update them. But I need example how to build it. May be there is another better way than use ModelMultipleChoiceField... Example of dirs - tree structure: |-L1_Dir#1 -|-L2_Dir#A-|-L3_Dir#P | | |-L3_Dir#Q | | | |-L2_Dir#B-|-L3_Dir#R | |-L3_Dir#S … -
Getting Django query list based on another table
I have models as below: Group Model class Group(model.Model): name = models.CharField(max_length=100, null=True, blank=True) GroupMember Model class GroupMember(model.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE, related_name='group_member_group') member = models.ForeignKey(User, on_delete=models.CASCADE, related_name='group_member_user') Course Model class Course(model.Model): name = models.CharField(max_length=100) GroupCourse Model class GroupCourse(model.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE, related_name='course_group') course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='group_course') CourseStaff Model class CourseStaff(model.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='course_staff_course') staff = models.ForeignKey(User, on_delete=models.CASCADE, related_name='course_staff_user') What I want is to get All the GroupMembers that does not exists in CourseStaff model for a specific course. For example: I have total 5 members in Group A Member 1 Member 2 Member 3 Member 4 Member 5 I have total 2 course in Group A Course 1 Course 2 Course 1 has two members: Member 1 Member 2 Course 2 has two members: Member 2 Member 3 What I want is to get Member 3-5 from GroupMember when querying for Course 1 Also get Member 1,4, 5 from GroupMember when querying for Course 2 How can I do that? Thanks -
Django: Query Group by Month with filling empty months
Trying to group by sales by month like below which works perfect monthbased = any_queryset.annotate(sales_month=TruncMonth('BidDate') ).values('sales_month' ).annotate(sum=Sum(F('Quantity')*F('SellPrice')) ) My question is about the months with no sales. I am using this result in a bar chart and if any month does not have sales then those months will not appear in the chart I want to show empty months with zero values. I did it like this # convert queryset to list of dicts monthbased_list = [{'sales_month': x['sales_month'], 'sum': x['sum']} for x in monthbased] # fill empty year and months for i in range(datetime.now().year-2, datetime.now().year+1): for j in range(1,13): if not any(d['sales_month'].month == j and d['sales_month'].year == i for d in monthbased_list): monthbased_list.append({'sales_month': datetime(i,j,1), 'sum': 0}) Is there a better way to do it? -
Cannot import is_safe_url from django.utils.http , alternatives?
I am trying to update my code to the latest Django version, The method is_safe_url() seems to be removed from new version of Django (4.0). I have been looking for an alternative for the past few hours with no luck. Does anyone know of any alternatives for the method in Django 4.0? -
Interface for DjangoFilterConnectionField
I have two classes class RegisteredUser(graphene.ObjectType): class Meta: interfaces = (BaseClient, ) name = graphene.String() group = graphene.String() policy = graphene.Int() event = graphene_django.filter.DjangoFilterConnectionField(AuthEvent, max_limit=15) Then I also have another class for users that have not signed up class NonRegisteredUser(graphene.ObjectType): class Meta: interfaces = (BaseClient, ) name = graphene.String() source = graphene.Int() event = graphene_django.filter.DjangoFilterConnectionField(NonRegisteredEvent, max_limit=15) And finally we have BaseClient class which is the common interface for both of the above classes class BaseClient(graphene.Interface): name = graphene.String() events = graphene_django.filter.DjangoFilterConnectionField('NotSureWhatToAdd', max_limit=15) @classmethod def resolve_type(cls, instance, info): if instance.type == 'RegisteredUser': return RegisteredUser return NonRegisteredUser Now everything works fine if I query "name" field but not sure how do I make 'events' field work since both have different DjangoFilterConnectionField. -
Cosine similarity query in elasticsearch
I have documents saved inside an index x which is inside another index y ie Maker/Ford and Maker/BMW, here documents are saved inside Ford which is inside Maker. Similarly for BMW. I need to find cosine similarity. I tried scripts, { "query": { "script_score": { "query": { "match_all": {} }, "script": { "source": "Ford['_vector'].size() == 0 ? 0 :cosineSimilarity(params.queryVector,'_vector')+1", "params": { "query_vector": [ 0,1,12,4 ] } } } } } { "script_score": { "query": {"match_all": {}}, "script": { "source": "cosineSimilarity(params.query_vector, '_vector') + 1.0", "params": {"query_vector": query_vector} } } } None of them really worked. What would be the solution? -
How to install django to the computer without internet connection (offline)
I am a beginner python programmer, I am trying to create django project (with PyCharm) on local computer without internet connection, but I am getting error from PyCharm that "install django failed" [Here you can see the error which shows PyCharm[][1]1 To my local computer I installed only PyCharm and Python 3.10.4 -
How to securely deploy a Django project on client machine server without code visibility?
I have a Django project which my Clients want to run on their server but I do not want them to have access or be able to read my code. I have looked at several blogs on internet but I could not find a solution to securely hide my code or encrypt them for non readability. I have tried creating binaries and also encrypting my .py files but it did not work. Is there a way to achieve this? -
How To Annotate Modified Related-Object Table In Django
I have a small business app which can be simplified as following models: class Client(..): name = CharField(...) class Sale(..): client = ForeignKey(Client, ...) item = CharField(...) time = DateTimeField(...) value = DecimalField(...) class Receive(..): client = ForeignKey(Client, ...) time = DateTimeField(...) value = DecimalField(...) Now I need a client-list-view displaying all clients with total sales, payments, receivable value and earliest date of sales unpaid ("edsu") that payment cannot cover. E.g. Client A 2022-01-01: bought Item X for $10, 2022-02-15: bought Item Y for $15, 2022-02-25: bought Item X for $10, and 2022-03-10: paid $12. Then Client A has a receivable of $23 and edsu of 2022-02-15. So far I use raw sql (as following) to do the query, and it works well. def client_list_view(request): ... clients = Client.objects.raw( raw_query = '''WITH app_balance AS ( SELECT id, client_id, item, time, val, SUM(sale) OVER wCN0 - SUM(receive) OVER wClt AS unpaid FROM ( SELECT id, client_id, item, time, val AS sale, 0 AS receive FROM app_sale UNION SELECT id, client_id, '' AS item, time, 0 AS sale, val AS receive FROM app_receive ) app_balance WHERE time < %(te)s::TIMESTAMPTZ WINDOW wClt (PARTITION BY client_id), wCN0 (wClt ORDER BY time ROWS BETWEEN UNBOUNDED … -
How to implement long polling with Django Apscheduler?
Really need help here. I'm trying to implement long polling with React as frontend and Django as backend. The plan right now is React will call the api endpoint, and wait till there result for it. The issue is, the function is trigger by apscheduler, but I have no idea on how to pass the return value out. I tried with apscheduler listener, but it only get the JobEvent itself, not the return value. I have think of put the value in request session, but same idea, since there no request passed in, how should I return or pass the value to session? I'm open to any solution, if there any other package allow me to schedule a weekly job and pass value as long polling. Much appreciate! -
i am creating my first project in django but i am getting error may i know the reason
may i know the reason why i am getting the yello mark or it is an error can yoou please rectify it -
How to pass two forms from one generic class in django
I want to pass two forms in one HTML template, I have two different models User and profile models.py: class Profile(models.Model): user = models.OneToOneField(User,null=True,on_delete=models.CASCADE) home_phone = models.CharField(max_length=20, blank=True, null=True) mobile_phone = models.CharField(unique=True, max_length=20,null=True) personal_id = models.CharField(max_length=30, blank=True, null=True) address_line_1 = models.CharField(db_column='address_Line_1', max_length=200,null=True) # Field name made lowercase. address_line_2 = models.CharField(db_column='address_Line_2', max_length=200, blank=True, null=True) # Field name made lowercase. city = models.CharField(max_length=50,null=True) country_fk = models.ForeignKey('Country', models.DO_NOTHING, db_column='country_FK',null=True) # Field name made lowercase. gender_fk = models.ForeignKey('Gender', models.DO_NOTHING, db_column='gender_FK',null=True) # Field name made lowercase. bdate = models.DateField(blank=True,null=True) def __str__(self): return str(self.user) members views.py class UserEditView(generic.UpdateView): form_class = EditProfileForm template_name = 'registration/edit_profile.html' success_url = reverse_lazy('home') def get_object(self): return self.request.user members forms.py class EditProfileForm(UserChangeForm): email = forms.EmailField(widget=forms.EmailInput(attrs={'class':'form-control'})) first_name = forms.CharField(max_length=100, required=True, widget=forms.TextInput(attrs={'class':'form-control'})) last_name = forms.CharField(max_length=100, required=False,widget=forms.TextInput(attrs={'class':'form-control'})) username = forms.CharField(max_length=100, required=False,widget=forms.TextInput(attrs={'class':'form-control'})) class Meta: model = User fields = ('username','first_name','last_name','email','password') class ProfileForm(ModelForm): Years = [x for x in range(1940,2021)] home_phone = forms.IntegerField(min_value=10000000,max_value=999999999,required=False,widget=forms.NumberInput(attrs={'class':'form-control'})) mobile_phone = forms.IntegerField(min_value=10000000,max_value=999999999,required=False,widget=forms.NumberInput(attrs={'class':'form-control'})) personal_id = forms.IntegerField(min_value=100000000000,max_value=9999999999999,required=False,widget=forms.NumberInput(attrs={'class':'form-control'})) address_line1 = forms.CharField(max_length=100, required=True, widget=forms.TextInput(attrs={'class':'form-control'})) address_line2 = forms.CharField(max_length=100, required=False,widget=forms.TextInput(attrs={'class':'form-control'})) city = forms.CharField(max_length=100, required=True,widget=forms.TextInput(attrs={'class':'form-control'})) Country = forms.ModelChoiceField(queryset=Country.objects,required=True,label=_('Country')) gender = forms.ModelChoiceField(queryset=Gender.objects,required=True,label=_('Gender')) bdate = forms.DateField(widget=forms.SelectDateWidget(years=Years)) class Meta: model = Profile fields = ('address_line_1','address_line_2','bdate','city','country_fk','gender_fk','home_phone','mobile_phone','personal_id') I want both forms show in my template to save the user information in User model and Profile model -
Django ModelChoiceField validation error using a custom query Manager
I am getting a validation error when trying to submit a form using a ModelChoiceField with a queryset using a custom Manager. The standard objects manager is also replaced with a custom manager that filters out archived objects. This is working well throughout the site My model (very simplified): # Use this as the default manager - filters out any records with an archivetype class ActiveManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(archive__isnull=True) # Alternative manager that returns non archived records and records archived with 'SYS' only class SysManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(models.Q(archive__isnull=True) | models.Q(archive='SYS')) class Inventory(models.Model): item = models.CharField(primary_key=True) description = models.CharField() archive = models.CharField(null=True, blank=True) objects = ActiveManager() objects_sys = SysManager() objects_all = models.Manager() # Default manager now objects_all class Building(models.Model): item = models.ForeignKey(Inventory, on_delete=models.PROTECT) I have a Building form that uses the Item field and adjusts the widget attributes (I need extra attributes in the HTML): class BuildingForm(forms.ModelForm): item = forms.ModelChoiceField(queryset=Inventory.objects_sys.all(), widget = forms.TextInput(attrs={ 'class': 'important', 'code': '1x1'})) Inventory.objects_sys.all() returns a queryset that includes an Inventory record with an item called 'INSPECT' while Inventory.objects.all() does not. This is expected and desired behavior in my case. The dropdown created shows the additional records returned by the custom manager (one of them … -
Why does my website work fine when tested locally, but the sessionid cannot be stored when using a domain name?
please help me!!! My project backend is django and frontend uses react. Local testing with localhost works fine. When I go online on the server and adjust the apache domain name, the sessionid cannot be automatically stored. I have tried many methods, but they are not available. But I found that if I don't use the apache proxy, it works fine if I use the ip directly, and the sessionid can also be stored. What is the reason for this? The code I put below. Django Settings INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'django_crontab', 'command_app', 'djcelery', 'corsheaders' ] MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', # 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware' ] CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = True # CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOWED_ORIGINS = [ 'http://react server ip:3000', 'https://react server ip:3000', 'http://localhost:3000', 'http://server ip:3000', 'https://server ip:3000', 'http://www.my domain name.com', 'https://www.my domain name.com', 'http://my domain name.com:3000', 'https://my domain name.com:3000', 'http://my domain name.com', 'https://my domain name.com', ] REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ("CustomAuthentication", ) } CORS_ALLOW_METHODS = ( 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', 'VIEW', ) CORS_ALLOW_HEADERS = ( 'XMLHttpRequest', 'X_FILENAME', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', 'Pragma', ) CACHES = { 'default': { 'BACKEND': "django_redis.cache.RedisCache", … -
I modify response.data in Django REST Framework view.py. Why am I getting an AttributeError during testing but not with actual API use?
My Django REST Framework API is working just as expected. In view.py, I modify OrderViewSet, def partial_update, to add another key/value pair to the response.data dict before it is saved to the db. It works without errors when I call the API with Postman. However, when I run tests for the same functionality it fails and returns: request.data["submission_date"] = datetime.now() AttributeError: This QueryDict instance is immutable Why would I get this error during testing if it is not occurring during actual API use? View.py class OrderViewSet(viewsets.ModelViewSet): """ Includes custom PATCH functionality """ queryset = Order.objects.all().order_by('-order_date') serializer_class = OrderSerializer authentication_classes = (authentication.TokenAuthentication,) permission_classes = [permissions.IsAuthenticated] def partial_update(self, request, *args, **kwargs): """ Update status and timestamp fields accordingly """ status = request.data['status'] if status == 'submitted': request.data["submission_date"] = datetime.now() if status == 'packaged': request.data["packaged_date"] = datetime.now() if status in ['sold', 'canceled', 'abandoned']: request.data["finished_date"] = datetime.now() return super().partial_update(request, *args, **kwargs) Test.py def test_patch_order_status_from_cart_to_submitted(self): """ test patching order status from cart to submitted """ order = sample_order(user=self.user) payload = { "status": "submitted" } res = self.client.patch(order_detail_url(order.id), payload) self.assertEqual(res.status_code, status.HTTP_200_OK) patched_order = Order.objects.get(id=order.id) self.assertEqual(patched_order.status, 'submitted') def test_submitted_timestamp(self): """ test that patching order status to submitted also leaves timestamp """ order = sample_order(user=self.user) payload = { … -
Unsupported operation error creating and saving json file
Ive been trying to save a json file created from a to a filefield, I got an unsuported operation error "not readable", this is my code from django.core.files.base import File @receiver(post_save,sender=ProyArq) def ifc_a_json(sender,instance,*args,**kwargs): if instance.arch_ifc: jsoon = ifc_2_json("path_to_file") json_file_nom = instance.nombre.replace(' ','')+'.json' with open(json_file_nom, 'w') as outfile: json.dump(jsoon, outfile, indent=2) json_fk = JsonIFC.objects.create(proy_fk=instance) json_fk.ifc_json.save(json_file_nom,File(outfile),True) im working with IFC files, and I want to store them also as json, I tried instead of saving the json as a JSONField, to save it as a foreign key file since the size of the json Im working are above 10mb, is this the best approach for this?? -
row data from axios in material-table only render after refreshing the page
Currently I am facing a problem that the data from axios POST request to material-table will not render immdiately. I need to refresh it in order to show it. I have a axios request structure like this: export default function DataWorker() { const [entries, setEntries] = useState({ data: [ { id: "", position: "", defect: "", tool: "" } ] }); const [state] = React.useState({ columns: [ { title: "Position", field: "position" }, { title: "Defect Type", field: "defect" }, { title: "Tool Decision", field: "tool" } ] }); const url = "http://127.0.0.1:8000/api/manual_ver_data/" useEffect(() => { axios.get(url) .then(response => { let data = []; response.data.forEach(el => { data.push({ id: el.id, position: el.position, defect: el.defect, tool: el.tool }); }); setEntries({ data: data }); }) }, []); return ( <MaterialTable columns={state.columns} data={entries.data} editable={{ onRowAdd: (newData) => new Promise(resolve => { setTimeout(() => { resolve(); const data = [...entries.data]; const populateData = (axiosResponse) => {data.push(axiosResponse)} axiosCallBack(populateData) console.log(data) function axiosCallBack (populateData) { axios.post(url, newData) .then(function(res){ populateData(res.data) }) }; setEntries({ ...entries, data }); }, 600) }) }} /> ) }; This is my view.py: @api_view(['GET', 'POST']) def TableViewList(request): if request.method == 'POST': serializer = TabelSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) After … -
I'd like to solve django webserver collectstatic error in ubuntu server
before i start my question, it is my first time to make a question in stackoverflow! I hope you all doing really really well for everything what you do. i try to get static file to using 'python manage.py collectstatic', but it's not working. I run my django project in Ubuntu 20.04.4, and using Nginx as a webserver, and Guicorn for WSGI server. Here is my error log, You have requested to collect static files at the destination location as specified in your settings. This will overwrite existing files! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: yes Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/devadmin/venvs/bio_platform/lib/python3.8/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/devadmin/venvs/bio_platform/lib/python3.8/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/devadmin/venvs/bio_platform/lib/python3.8/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/home/devadmin/venvs/bio_platform/lib/python3.8/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/home/devadmin/venvs/bio_platform/lib/python3.8/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 209, in handle collected = self.collect() File "/home/devadmin/venvs/bio_platform/lib/python3.8/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 135, in collect handler(path, prefixed_path, storage) File "/home/devadmin/venvs/bio_platform/lib/python3.8/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 368, in copy_file if not self.delete_file(path, prefixed_path, source_storage): File "/home/devadmin/venvs/bio_platform/lib/python3.8/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 278, in delete_file if self.storage.exists(prefixed_path): File "/home/devadmin/venvs/bio_platform/lib/python3.8/site-packages/django/core/files/storage.py", line 362, in exists … -
Django HTMX: How to Remove Search List Group Suggestion When User Clear the Input Keyword in the Search Field?
I've been working on a search function for Django project using HTMX. The search function can successfully generate list group suggestion based on the keyword that user input by using hx-trigger="keyup changed delay:500ms". However, when user clear the search field, the list group suggestion still displayed on the page. How can I possibly remove the list group suggestion? Here are some snippet from my code: search.html <div class="container-fluid p-2"> {% csrf_token %} <input type="text" hx-get="{% url 'search-obj' %}" hx-target="#result" hx-trigger="keyup changed delay:500ms" name="search" class="form-control" placeholder="Search Object Here..."/> </form> </div> <div id="result"></div> searchresult.html {% if results %} {% csrf_token %} <ul class="list-group"> {% for object in results %} <li class="list-group-item justify-content-between align-items-center"> {{object.name}} </li> {% endfor %} </ul> {% else %} <p>No result</p> {% endif %} views.py def searchobj(request): searchtxt = request.GET.get('search') results = Object.objects.filter(name__icontains=searchtxt) context = {'results' : results} return render(request, 'base/searchresult.html', context) urls.py urlpatterns = [ path('', views.home, name="home"), path('search-line/', views.searchobj, name="search-obj"), ] -
How to count a single field of a django queryset with multiple group by?
Let's say I have a queryset qs. I'm grouping by the queyset as follow: ( qs.annotate( catering_price_enabled=F("outlet__library__settings__sligro_catering_price_enabled"), ) .values("assortment_sync_id", "catering_price_enabled") .order_by("assortment_sync_id", "catering_price_enabled") .distinct("assortment_sync_id", "catering_price_enabled") ) And I'm getting something like: <QuerySet [ {'assortment_sync_id': '01234', 'catering_price_enabled': False}, {'assortment_sync_id': '01234', 'catering_price_enabled': None}, {'assortment_sync_id': '56789', 'catering_price_enabled': None}, ]> What I'm trying to do is to annotate this queryset so I can eventually filter for values > 1. In other words, each assortment_sync_id can have only value of catering_price_enabled. If I add .annotate(count=Count("assortment_sync_id")) django raises NotImplementedError: annotate() + distinct(fields) is not implemented. I tried this approach because it obviously works with just one field. How can I get the expected output below? <QuerySet [ {'assortment_sync_id': '01234', 'catering_price_enabled': False, 'count': 2}, {'assortment_sync_id': '01234', 'catering_price_enabled': None, 'count': 2}, {'assortment_sync_id': '56789', 'catering_price_enabled': None, 'count': 1}, ]> -
Change Header Key for rest_framework's TokenAuthorization
By default, rest_framework's TokenAuthentication uses the "Authorization" key in the header, and looks for the keyword "Token" when authenticating requests. Authorization: Token [value] How do I change it to use the "API-AUTH" key instead, and no keyword? API-AUTH: [value] -
How can I add a default value for DateField in a model?
Using Django/python. So I have a 'food' model that is taking multiple user inputs, one of which is 'type' and has the options of 'fresh' and 'pantry'. Another is a DateField that represents an expiration date. What i want is that when the user selects 'fresh' in the type field, I want the default date to be todays date + 3 days. If the user selects pantry then I want to use the date that is entered into my food model. exp = models.DateField('exp date', blank=True, null=True) Im not sure if more of my code will be needed or if what im asking is possible but any help would be appreciated.