Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How To Clear self.add_error in Django if user clicks on browser back button?
I have a FORMVIEW where a user selects a value from a dropdown, and if they select the value, and click submit, it performs an HTTPResponseRedirect to a URL and all is well. If they forget to enter a value and click submit, they get an error message telling them to choose a value. I do a clean on the form to figure this out. This all works just fine. The issue is if the user gets an error message, then adds a value and then displays the desired output. If they then click the back button on the browser window after viewing the output, the error message is still displayed. I have been able to work around this by including a NeverCacheMixin to the form, but when the user clicks on the back button, they get an ugly Confirm Form Resubmission page. The user is just looking up a value, so maybe there is a better way to approach this? There are no updates or deletes involved, it's strictly a lookup on one page that does an HttpResponseRedirect to another. Here is my FORMVIEW... class AuthorLookupView(LoginRequiredMixin,FormView): form_class = AuthorLookup template_name = 'author_lookup.html' def form_valid(self, form): authorbyname = form.cleaned_data['dropdown'] return … -
Django Import Export export pk instead of name after using ForeignKeyWidget?
I am using django-import-export for exporting and importing data in csv. I have used example according to given doc of django-import-export. I have used: Python - version 3.7 django -version 2.2 django-import-export - 1.2.0 https://django-import-export.readthedocs.io/en/latest/api_widgets.html#widgets Django import-export display manytomany as a name instead of ids when exporting to csv models.py: class Author(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Book(models.Model): name = models.CharField('Book Name', max_length=100) author = models.ForeignKey(Author, blank=True, null=True, on_delete=models.CASCADE) author_email = models.EmailField('Author Email', max_length=75, blank=True) imported = models.BooleanField(default=False) published = models.BooleanField('Published', blank=True, null=True) price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) categories = models.ManyToManyField(Category, blank=True) def __str__(self): return self.name resources.py from import_export import resources, fields from import_export.widgets import ForeignKeyWidget from .models import Person, Book, Author class PersonResource(resources.ModelResource): class Meta: model = Person class BookResource(resources.ModelResource): author = fields.Field( column_name='author', attribute='author', widget=ForeignKeyWidget(Author, 'name')) class Meta: model = Book fields = ('author__name', ) admin.py from django.contrib import admin from import_export.admin import ImportExportModelAdmin from .models import Book, Author, Category @admin.register(Book) class BookAdmin(ImportExportModelAdmin): pass @admin.register(Author) class AuthorAdmin(ImportExportModelAdmin): pass @admin.register(Category) class CategoryAdmin(ImportExportModelAdmin): pass I expect that while exporting data of books in csv, I will get name of author in author column but got pk. And … -
django-tables2 not displaying column titles
I'm generating a leaderboard using django-tables2 based on this model (in users/models.py): class CustomUser(AbstractUser): points = models.DecimalField( max_digits=20, decimal_places=2, default=Decimal('1000.00'), verbose_name='User points') In tables.py, I select username and points, and order by the latter: class UserTable(tables.Table): class Meta: model = CustomUser fields = ('username','points') order_by = '-points' template_name = 'django_tables2/bootstrap.html' In views.py, I have def leaderboard_list(request): table = UserTable(CustomUser.objects.all()) RequestConfig(request).configure(table) return render(request, 'leaderboard.html', { 'table': table }) Finally, this gets rendered in the leaderboard.html template with {% load render_table from django_tables2 %} and {% render_table table %}. The table renders fine, but without any column headers. I added the verbose_name to the points field of the CustomUser model in light of this suggestion, under the assumption that this should show by default (as per this), but to no avail. What am I doing wrong here? -
Processing JSON with AJAX from a search
I have: {% extends 'base.html' %} {% block content %} <form method="GET" action="{% url 'libros:buscar' %}" id="buscador-libros"> <div> <input type="text" , name="titulo" /> <input type="submit" value="Buscar" /> </div> </form> <script type="text/javascript"> $(document).ready(function() { $("#buscador-libros").submit(function(e) { e.preventDefault(); $.ajax({ url: $(this).attr("action"), type: $(this).attr("method"), data: $(this).serialize(), success: function(json) { console.log(json); } }); }); }); } </script> {% endblock content %} I get the json response from the server side fine but don't know why I can not show it in console or why is this still redirecting me. What am I doing wrong? Edit: I add jquery in 'base.html' -
Python Django autocomplete light the results could not be loaded
I am trying to add autocomplete light to my project, but I am not able to. If I want to find anything in the form it says: The results could not be loaded, TypeError: 'bool' object is not callable. I am using Python version 3.7 and django-autocomplete-light version 3.3.5 The project is web app to track orders which are assigned to the users. to the mysite/settings.py I added: INSTALLED_APPS = [ 'dal', 'dal_select2', 'crispy_forms', 'myapp', to the mysite/myapp/urls.py I added: path('autocomplete/', login_required(views.OrderAutocomplete.as_view()), name="autocomplete"), to the base.html: <head> {% load staticfiles %} ... <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script> and to the new_order.HTML: <form method="POST"> {% csrf_token %} {{ form|crispy }} {{ form.media }} <input type="submit"> </form> To the mysite/myapp/views.py I added: class ObjednavkaAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): # Don't forget to filter out results depending on the visitor ! if not self.request.user.is_authenticated(): return Objednavka.objects.none() qs = Order.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs and to the mysite/myapp/forms.py I added: class OrderForm(forms.ModelForm): user_auto = forms.ModelChoiceField(queryset=Order.objects.all(), widget = autocomplete.ModelSelect2(url='autocomplete')) class Meta: model = Order fields = ["user_auto"] mysite/myapp/models.py: from dal import autocomplete class Order(models.Model): ... user = models.ForeignKey(MyUser, on_delete=models.CASCADE) class MyUser(models.Model): eid = models.CharField(max_length=7) I am sorry for posting so much code. If I try … -
what is wrong with the update function?
i have an update function that is written in django views and that must edit or update the data in the database based on the selected ID and display the data in the form in update page once the user finish the update and click edit it must take him to the list page where it shows the updated data. views.py def update(request,pk): #deny anonymouse user to enter the create page if not request.user.is_authenticated: return redirect("login") else: # dbEntry = suspect.objects.filter(pk =pk) dbEntry = suspect.objects.get(pk =pk) print( "db entry : ",dbEntry) if request.method == 'POST': fname = request.POST['FName'] dbEntry = suspect.objects.filter(pk = pk).update(suspect_name = fName) #INSERT INTO TABLE VALUES ....... dbEntry.save() #to save into DB return render(request,'blog/update.html', {"dbEntry":dbEntry}) update.html {% extends "base.html" %} {% load static %} {% block body %} <head> <link rel="stylesheet" type="text/css" href="{% static '/css/linesAnimation.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/input-lineBorderBlue.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/dropDown.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/home.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/meta-Input.css' %}"> <meta name= "viewport" content="width=device-width, initial-scale=1.0"> <script type="text/javascript" src="{% static '/js/jquery-3.1.1.min.js'%}"></script> <title>Welcome</title> </head> <body> <div class="lines"> <div class="line"></div><div class="line"></div> <div class="line"></div><div class="line"></div> <div class="line"></div><div class="line"></div><div class="line"></div> </div> <form method = "POST" enctype="multipart/form-data"> {% csrf_token … -
How to link guest and user checkout together?
I'm very new to Django and I'm confused with the checkout. I have the "accounts" app for user to enter their profile and I want to link it with the checkout but also include guest checkout. Right now I'm good to the guest-checkout but I cant link the user info from "accounts" app to the checkout. The error says " IntegrityError at /usercheckout/ NOT NULL constraint failed: accounts_profile.user_id " accounts/models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=255, default='') last_name = models.CharField(max_length=255, default='') email = models.EmailField(default='none@email.com') birth_date = models.DateField(default='1999-12-31') address = models.TextField(default='') mobile = models.CharField(max_length=255, default='') def __str__(self): return self.user.username def __str__(self): return 'Order {}'.format(self.id) def create_profile(sender, **kwargs): if kwargs['created']: profile = Profile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) orders/models.py class Order(models.Model): first_name = models.CharField(max_length=60) last_name = models.CharField(max_length=60) email = models.EmailField() address = models.CharField(max_length=150) postal_code = models.CharField(max_length=30) city = models.CharField(max_length=100) mobile = models.IntegerField(default=0) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False) class Meta: ordering = ('-created', ) def __str__(self): return 'Order {}'.format(self.id) def get_total_cost(self): return sum(item.get_cost() for item in self.items.all()) class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE) orderu = models.OneToOneField(Profile, on_delete=models.CASCADE) product = models.ForeignKey(Product_info, related_name='order_items', on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField(default=1) def __str__(self): return '{}'.format(self.id) def get_cost(self): return self.price * … -
How to change the url password_reset link in django?
I have a users app and I have links in urlpatterns but the problem is whenever I click on the Forgot Password link, instead of going to password_reset which I have set it leads me userspassword_reset/ url. userspassword_reset/ is a password reset page in admin page but I want it to be in custom page. path('users', include('django.contrib.auth.urls')), path('password_reset/',auth_views.PasswordResetView. as_view(template_name='users/password_reset.html') path('password_reset_done/', password_reset_done, name='password_reset_done') It should send me to this page {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {%csrf_token%} <fieldset class="form-group"> <legend class="border-bottom mb-4" style="font-size: 50px"> Reset Password</legend><br> {{form|crispy}} </fieldset><br> <div class="form-group"> <button class="btn btn-outline-info" type="submit"> Send Confirmation Link</button> </div> </form> </div> <br> {% endblock %} -
Server Error (500) when change database user password
i changed database user password and I got this error "Server Error (500)" what should i do ? [debug=False] in production -
How to pass detail url inside the list in DRF
Here i am trying to do CRUD operations with the django-rest framework and the following code works fine also but the one thing i want to change is i want to give the detail url inside the list..How can i do it ? urls.py path('create/',CategoryCreateAPIView.as_view(),name='category-create'), path('list/',CategoryListAPIView.as_view(),name='category-list'), path('detail/<int:pk>/',CategoryDetailAPIView.as_view(),name='category-detail') views.py class CategoryCreateAPIView(generics.CreateAPIView): queryset = Category.objects.all() serializer_class = CategorySerializer permission_classes = [IsAdminUser] class CategoryListAPIView(generics.ListAPIView): queryset = Category.objects.all() serializer_class = CategorySerializer permission_classes = [IsAdminUser] class CategoryDetailAPIView(generics.RetrieveUpdateDestroyAPIView): queryset = Category.objects.all() serializer_class = CategorySerializer permission_classes = [IsAdminUser] with the list url it displays the data like this.which is fine. HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "count": 3, "next": null, "previous": null, "results": [ { "id": 1, "name": "category1", "description": "description", }, { "id": 2, "name": "category2", "description": "description", ...................... But when i have to go for the details of id 2 then i have to enter /category/detail/1/ and then i can view the deatils of that id.Is there any solution so that i can pass my detail url inside the every id in the list? The result i want is : HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "count": 3, "next": null, "previous": null, "results": … -
Sessions are destroying when user redirect from cc avenue payment page in python
when user click on pay user navigate to payment page integrated payment page using html post request. when user back to my application from payment page sessions are destroyed Please Help If any one know Solutions Thank you -
Filtering through two querysets with a many to many relationship in between
I have 3 different models, activity, category and sector. There's a many to many relationship between category and activity, and a one to many relationship between category and sector (a category to one sector). In a form I am getting the sector (mandatory) and I can also get the category (non mandatory field). I stock that into the session then I want to select every activities that are either in the category selected (if any selected) or in the sector. When a category is selected it's fine I just filter activities on activities_have_category. But for the case where only sector I can't filter it properly. I tried the solution to a quite similar problem but it didn't work... Solution tried: activity.objects.filter(category__sector__sector_name =request.session['sector']['sector_name']) Result: Cannot resolve keyword 'category' into field. Choices are: activities_have_category, activities_have_countries, activities_have_output_outcome_impact, activity_name, description, outcome_impact, output_outcome, product_service What I would like to get in SQL: SELECT activity_name FROM activity WHERE activities_have_category IN (SELECT category_name FROM category WHERE category_sector = "sector selected") class sector(models.Model): sector_name = models.CharField(max_length=255, primary_key=True) description = models.TextField() def __str__(self): return self.sector_name class category(models.Model): category_name = models.CharField(max_length=255, primary_key=True) description = models.TextField() category_sector = models.ManyToManyField('sector') def __str__(self): return self.category_name class activity(models.Model): activity_name = models.CharField(max_length=255, primary_key=True) description = … -
How to define an in-store cash-payment-method in django-oscar 2.0
I would like to implement cash payments, wherein the customer picks up his order in store, and pays the same there. There will also be an option later on for customers to pay cash upon delivery of their orders (note: I understand that there is an oscar cash on delivery app, but I am asking regardless). What is oscar's new recommended way to define cash payment methods in version 2.0? Previously, (though I can no longer find the documentation), payment methods were defined by expanding a base payment method like so: # mystore/forked_apps/payment/methods.py class Base(object): """ Payment method base class """ code = '__default__' name = 'Default payment' description = '' enabled = False default = False class CashOnPickup(Base): code = 'cash_on_pickup' name = 'Cash on Pickup' description = 'Pay when you pick up your items' enabled = True default = True However, the new documentation mentions the use of the SourceType, Source, and Transaction models, and I can no longer find the previous documentation regarding defining methods like above. As such, what is the recommended manner to define an in-store cash payment method in django-oscar 2.0? Is defining methods in a methods.py file no longer the way to go? … -
Slack API ConnextionError but still working
I want to post a message to Slack using a bot, so I created a service to do that (in Flask). Now I call this service using requests (Django). data = json.loads(json.dumps(_data)) headers = { 'Content-Type': "application/json", 'cache-control': "no-cache", } r = requests.post(url, json=data, auth=(username, password), headers=headers) While the bot is posting on Slack and everything is working like expected, I'm having an error message and this is confusing: ('Connection aborted.', BadStatusLine("HTTP/1.0 0{ 'ok':True, 'channel':'xxxxxxxxxxx', 'ts':'1563789414.000600', 'message':{ 'type':'message', 'subtype':'bot_message', 'text':'xxxxxxxxxxx', 'ts':'1563789414.000600', 'username':'xxxxxxxxxx', 'bot_id':'xxxxxxxxxxx' }, 'headers':{ 'Content-Type':'application/json; charset=utf-8', 'Content-Length':'220', 'Connection':'keep-alive', 'Date':'Mon, 22 Jul 2019 09:56:54 GMT', 'Server':'Apache', 'X-Content-Type-Options':'nosniff', 'X-Slack-Req-Id':'1851de9e-59ec-45a7-be61-107a092e6371', 'X-OAuth-Scopes':'admin,identify,bot,groups:read,usergroups:read,chat:write:user,chat:write:bot,groups:write', 'Expires':'Mon, 26 Jul 1997 05:00:00 GMT', 'Cache-Control':'private, no-cache, no-store, must-revalidate', 'Access-Control-Expose-Headers':'x-slack-req-id, retry-after', 'X-XSS-Protection':'0', 'X-Accepted-OAuth-Scopes':'chat:write:bot', 'Vary':'Accept-Encoding', 'Pragma':'no-cache', 'Access-Control-Allow-Headers':'slack-route, x-slack-version-ts', 'Strict-Transport-Security':'max-age=31536000; includeSubDomains; preload', 'Referrer-Policy':'no-referrer', 'Content-Encoding':'gzip', 'Access-Control-Allow-Origin':'*', 'X-Via':'haproxy-www-n3u5', 'X-Cache':'Miss from cloudfront', 'Via':'1.1 d6561aeeccb210202cf78b99f07c5235.cloudfront.net (CloudFront)', 'X-Amz-Cf-Pop':'CDG3-C2', 'X-Amz-Cf-Id':'Y4CJp-NBWSkdNYXm8bfTCdhuFPL1sn6johYZqkmv_wsXfaq0kcA7TQ==' } }\r\n")) Calling the service using a simple curl works fine without any error: curl -d "@data.json" -H "Content-Type: application/json" -X POST http://0.0.0.0:8004/ --user xxxxx:xxxxx Do you see the problem ? -
How to add CSRF token for Ajax Request not using jQuery
I want to send some data from the javascript file to the views file in my Django app using an Ajax request. However I am doing this using only Javascript as I am not familiar with jQuery and don't now how to add the CSRF token. Here is my Javascript Code: const request = new XMLHttpRequest(); request.open("POST", "/list"); var csrftoken = Cookies.get('csrftoken'); let data = { items: JSON.stringify(items), CSRF: csrftoken } request.send(data); I have tried using Cookies.get('csrftoken') and getCSRFTokenValue() but am unsure how to send the token once acquired. -
django admin filter for dictionary field
I have a model with a dictionary field inside it. for admin page of this model, I have one of the list_filter as a value from a foreign key referencing to another model. what i want is to filter out the keys in the dictionary field based on this list_filter . As an example model A has fields : x,y,z where y is dictionary field its admin has a list filter L that needs to filter keys in y based on its value selected . How is this possible to achieve in a clean way ? thanks in advance -
Restframework restore request, how can i prevent this
I wrote a middleware to authenticate, after authentication, I want to modify request.POST to view, view use two decorators of restframework. When I delete the two decorators, it works well, the request is changed.How can I use the two decorators and change the request at the same time. Middleware code: class ApiAuthenMiddleware: def init(self, get_response): self.get_response = get_response def __call__(self, request): sign = request.POST['sign'] nonce_str = request.POST['nonce_str'] password = request.POST['password'] key = f"{f'{password}{nonce_str}'[:24]:0<24}" data = request.POST['data'] if encrypt(data, key) != sign: pass else: request.POST = QueryDict(urlencode(json.loads(data))) response = self.get_response(request) return response View Code: @api_view(['POST']) @renderer_classes([TemplateHTMLRenderer, JSONRenderer]) def package_list(request): iccid = request.POST['iccid'] serializer = BLEDataPlanSerializer(BLEDataPlan.objects.filter(card__iccid=iccid)) data = serializer.data return Response(data) -
how to pass csrf-token in first request
my question is how cookies works, this question is arrived in my mind when i loaded my page for first time i got this REQUEST HEADER Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3 Accept-Encoding: gzip, deflate, br Accept-Language: en-GB,en;q=0.9,en-US;q=0.8 Cache-Control: max-age=0 Connection: keep-alive Cookie: csrftoken=gsZxmbW4XUpE6YnaQhlrAx9JduyExVgzWEo4fXhcY4V3fbHWVtwf0msbDQDT5r43 Host: 127.0.0.1:8000 Upgrade-Insecure-Requests: 1 when first request was sent it already had csrftoken in cookie i tried same in incognito window than also i got same result. how can my browser already have cookie without any communication to server i am working on django with angular 7, problems is that i am sending my request from angular this.http.post('http://127.0.0.1:8000/',data, {observe : "response", withCredentials: true } )} but in response of that i am not getting any csrftoken in setcookie . please help me ..... sorry for adding two problems in one question but both are indirectly connected to each other -
How to modify router and viewsets for template rendering
I have a simply CRUD application with Rest-Framework my views, serializers and routers is created dynamically. I used a simple code from DRF docs like that: VIEWS: class PersonViewSet(viewsets.ModelViewSet): serializer_class = PersonSerializer queryset = Person.objects.all() SERIALIZERS: class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person fields = '__all__' URL: router = routers.SimpleRouter() router.register(r'persons', PersonViewSet) Now I have to do smth for displaying data for end-users. My goal is: 1. Play 1-2 weeks with build-in django functionality for frontend development 2. Consider about vue.js as a frontend framework. So I have to use django and DRF as a backend (this is for sure). I have some trouble with template rendering. Now I create a simple HTML templates and try to implement them. There are some problems when using them with ViewSets. Seems that I have to use another parent class for views. Could you provide me some examples how should I change my views and router? I already tried to use simply APIView, but seems that routers works only with viewsets. -
Django, how to use the admin autocomplete field in a custom form
In the Django admin interface you can set a field to be a autocomplete field, e.g.: autocomplete_fields = ('countries', ) This works great for admin pages, how does one use the autocomplete field in a custom view/form? My research points towards django-autocomplete-light, but it seems non-ideal to install a 3rd party package when Django already has the functionality built-in. -
Python-Tweepy-How to disconnect all streams where is_async=True in tweepy with streams.disconnect()?
I have 2 functions one is for start stream and other is for stop stream with is_async=True, and now I can start multiple but when I call stop stream function it only stops the first stream in the thread. For Start Stream simply calling this function def startStream(): global myStreamListener myStreamListener = MyStreamListener() global myStream myStream= tweepy.Stream(auth=api.auth, listener=myStreamListener,truncated=False) myStream.filter (track=[track], follow=[follow], locations=location1, is_async=True) For Stop Stream calling this function def stopStream(): myStream.disconnect() Now the problem is I can start multiple crawler with startStream function but unable to stop all crawler with stopStream. Question: Now my first question is how to stop all streams one by one or on call with stopStream function? Thanks...!! -
Parse QueryDict data
Little new to django, I'm running python scrip to fetch the data and like to display in HTML table tags. Python script works and gather the data in the following: [{'Device': 'device01', 'Port': 'ETH1/5', 'Provider': 'L3', 'ID': 1111, 'Remote': 'ISPCircuit', 'Destination Port': 'ISPPort'}, {'Device': 'device02', 'Port': 'ETH1/5', 'Provider': 'L3', 'ID': 2222, 'Remote': 'ISPCircuit', 'Destination Port': 'ISPPort'}] When run the python script in Django in the view.py, I store the output in the following: if form.is_valid(): ## Python script GatherData file output = gatherdata(location) data = QueryDict(output, mutable=True) ## Dict format to fetch context = {'data': data } The output looks like the following: <QueryDict: {"[{'Device': 'device01', 'Port': 'ETH1/5', 'Provider': 'L3', 'ID': 1111, 'Remote': 'ISPCircuit', 'Destination Port': 'ISPPort'}, {'Device': 'device02', 'Port': 'ETH1/5', 'Provider': 'L3', 'ID': 2222, 'Remote': 'ISPCircuit', 'Destination Port': 'ISPPort'}]\n": ['']}> Explain above, How to parse the value from the given data, to html template Given above, Thank for the ideas and suggestion. I have tried, json.loads(output) but thru errors. I have tried data = literal_eval(context['data']) to remove the strings. -
'Invalid default value error' in models file
I was trying to create a "currency" column which would consist of choices for different currencies. I tried everything but couldn't resolve "django.db.utils.OperationalError: (1067, "Invalid default value for 'currency'")" error. Here is my models.py file. class Products(models.Model): INR='₹' USD='$' CURRENCY_LIST=[(INR,'INR'),(USD,'USD')] subcategory=models.ForeignKey(Subcategory,on_delete=models.CASCADE) category=models.ForeignKey(Category,default='',on_delete=models.CASCADE) name=models.CharField(max_length=30) price=models.DecimalField(max_digits=7,decimal_places=2,default=0) currency=models.CharField(max_length=2,choices=CURRENCY_LIST,default=INR) class Meta: db_table='products' @property def combined(self): return self.price+self.currency def __str__(self): return self.name How to resolve this error? -
what is django datetime field format
I send django datetime field data to client in string type my question is how i can convert this string to python datetime? my datetime is: "2019-07-22T10:01:40.876487+04:30" I want to do something like this: datatime.datetime('2019-07-22T10:01:40.876487+04:30', '<django default datetime format>') and I expect to have: <class 'datetime.datetime'> WHAT IS DJANGO DEFAULT DATETIME FORMAT? OR HOW I CAN CONVERT THIS STRING TO DATETIME? -
How to decouple local directory and Heroku project
I am developing an app with Django and I successfully pushed it on Heroku. This app has a database and a form to allow users to fill the database. I have coupled the local directory and Heroku, so that both if I run the server by command prompt, or if I access the app, and submit the form, my database get changed. Now I want to make some experiments on the local database without changing the one on Heroku. Is it possible? Can I do it by just commenting the database URL in settings.py ? I have searched for this matter on Google but I don't know the name it, so that I cound not find proper answer.