Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploying django app to heroku - can't find new uploaded files
I build this site "https://bookzd.herokuapp.com" to download books but when i choose a book and try to downloaded it can't be downloaded, it says 404 not found. I did run Django app locally and it work fine. -
Django Deployment on Heroku Issue
Folks I've been steadily working through error codes trying to deploy a Django app on Heroku since yesterday. Design/front end is more my skillset, and I'm struggling to get my head around it. I've worked through a lot of questions and fixes here that have got me further, but there's still something breaking the deployment, even though it says it's built and deployed. What else should I include in this post to help solve this issue? Many thanks in advance! Sam 2021-11-08T14:16:21.000000+00:00 app[api]: Build succeeded 2021-11-08T14:16:23.704273+00:00 heroku[web.1]: Starting process with command `gunicorn Bax-Conversions.wsgi --log-file -` 2021-11-08T14:16:25.194030+00:00 app[web.1]: [2021-11-08 14:16:25 +0000] [4] [INFO] Starting gunicorn 20.1.0 2021-11-08T14:16:25.194734+00:00 app[web.1]: [2021-11-08 14:16:25 +0000] [4] [INFO] Listening at: http://0.0.0.0:15090 (4) 2021-11-08T14:16:25.204556+00:00 app[web.1]: [2021-11-08 14:16:25 +0000] [4] [INFO] Using worker: sync 2021-11-08T14:16:25.214346+00:00 app[web.1]: [2021-11-08 14:16:25 +0000] [9] [INFO] Booting worker with pid: 9 2021-11-08T14:16:25.222572+00:00 app[web.1]: [2021-11-08 14:16:25 +0000] [9] [ERROR] Exception in worker process 2021-11-08T14:16:25.222574+00:00 app[web.1]: Traceback (most recent call last): 2021-11-08T14:16:25.222588+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker 2021-11-08T14:16:25.222588+00:00 app[web.1]: worker.init_process() 2021-11-08T14:16:25.222588+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 134, in init_process 2021-11-08T14:16:25.222589+00:00 app[web.1]: self.load_wsgi() 2021-11-08T14:16:25.222589+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi 2021-11-08T14:16:25.222589+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2021-11-08T14:16:25.222590+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi 2021-11-08T14:16:25.222590+00:00 … -
How can I handle multiple requests at the same time in Django?
I'm currently writing an API in which a user could transfer money from their account to a phone but I'm facing an issue which is the user can call the API more than once at the same time and ask for transferring the money. Normally the balance of his account wouldn't be correct after the calls so I searched a lot and found out that I can use atomic transactions and lock the database. Now if the user uses the API for example twice, one of them runs correctly but the other one gets django.db.utils.OperationalError: database is locked error. Any idea how can I handle both of them correctly? (I could use a while and wait until the database gets unlocked but I rather don't do that) models.py @transaction.atomic() def withdraw(self, amount, phone, username): property = transferLog.objects.filter(username=username).order_by('-time').select_for_update()[0] if property.property >= int(amount): self.username = username self.property = property.property - int(amount) self._from = username self._to = phone self.amount = int(amount) self.time = str(datetime.datetime.now()) self.save() return {'result': 'success', 'message': 'transfer complete', 'remaining': self.property} else: return {'result': 'error', 'message': 'not enough money'} -
how to save csv data in list in django
Here soil_type should be in list format in database , here soil_type can be multiple Let us consider my views.py as class HorticultureItemsUpload(View): field_map = { 'PLANT_NAME': 'item_name', 'ALTERNATE_NAME': 'common_name', 'PLANT_CODE': 'plant_code', 'USER_TEXT_9': 'tree_type', 'USER_TEXT_8': 'categories', 'USER_TEXT_10': 'growth_rate', 'USER_TEXT_13': 'crown_shape', 'USER_TEXT_11': 'season_interest', # multiple 'USER_TEXT_20': 'ornamental_flower', 'USER_TEXT_12': 'height_at_maturity', 'USER_TEXT_14': 'soil_type', # multiple 'USER_TEXT_15': 'exclude_intolerant', # multiple # 'USER_TEXT_19': 'recommended_for', 'USER_TEXT_16': 'recommended_for', # Multiple 'USER_TEXT_17': 'summer_foliage_colour', 'FLOWER_COLOUR': 'flower_colour', 'PLANT_NOTES_TXT': 'description', 'PZ_CODES': 'pz_code', 'LABEL_TXT': 'label_text', } def get(self, request): self.currency_choices = [choice[0] for choice in CURRENCY_CHOICES] self.uom = [unit.name for unit in UnitOfMeasure.objects.all()] return render(request, 'jobs/upload_items_csv.django.html', { 'uom': self.uom, 'currency_choices': self.currency_choices }) def get_values_remapped(self, row): self.field_errors = {} remapped_dict = {self.field_map[key]: row[key] for key in self.field_map} return remapped_dict def post(self, request): client = request.user.client self.user = request.user self.client = client self.currency_choices = [choice[0] for choice in CURRENCY_CHOICES] self.uom = [unit.name for unit in UnitOfMeasure.objects.all()] data = { 'uom': self.uom, 'currency_choices': self.currency_choices } csv_file = request.FILES['items_csv'] reader = csv.DictReader(csv_file) error_rows = [] errors = [] count = 0 duplicates = 0 try: with transaction.atomic(): for line_number, row in enumerate(reader): try: remapped_row = self.get_values_remapped(row) if JobItems.objects.filter( item_name=remapped_row['item_name'], client=self.client, plant_code=remapped_row['plant_code']).exists(): duplicates += 1 continue except KeyError as e: messages.error(request, 'Column "%s" (case sensitive) was not … -
Django Rest-framework, JWT authentication
I'm newbie in Django Restframework. I use JWT to make login, register API, everythings worked well, I want to GET a user information with authenticated (tokens). This is my code for UserViewSet class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer authentication_classes = [IsAuthenticated,] I've tested on Postman but i received: "'IsAuthenticated' object has no attributes 'authenticate'" REST_FRAMEWORK = { 'NONE_FIELD_ERRORS_KEY':'error', 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } Could you please to help me to solve this promblem? Thank you very much. -
Django Error: RecursionError: maximum recursion depth exceeded
When I execute the python3 manage.py runserver command it gives me the error RecursionError: maximum recursion depth exceeded. I am currently using Django version 3.2 and using the Django project to learn in django https://docs.djangoproject.com/en/3.2/intro/tutorial01/ and I use pythonanywhere, but before the error it gives me this File "/usr/local/lib/python3.9/site-packages/django/urls/resolvers.py", line 413, in check messages.extend(check_resolver(pattern)) File "/usr/local/lib/python3.9/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/usr/local/lib/python3.9/site-packages/django/urls/resolvers.py", line 413, in check messages.extend(check_resolver(pattern)) File "/usr/local/lib/python3.9/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/usr/local/lib/python3.9/site-packages/django/urls/resolvers.py", line 413, in check messages.extend(check_resolver(pattern)) RecursionError: maximum recursion depth exceeded -
Django searching for a particular record
Im trying to search for a particular record, based on the ID i have input into the button on the UI: <button class="btn btn-sm btn-icon btn-icon-only btn-outline-primary" type="button" value={{ skill.id }} name='editbut'> I have checked and the ID reflects correctly In the view, I have the below. This works when I hardcode in the value, but when I try to extract it from the button value, it fails. Any help would be amazing!! Thanks def edit_skill(request): skillid = request.POST.get('editbut') t = skills.objects.get(id=skillid) t.status = 'closed' t.save() # this will update only messages.success(request, ('Changes saved')) return redirect('index') -
Get blank page when deployed django app using rest framework and react js (simpleJWT) on raspberry pi
i open my website, it shows a blank webpage and i checked the errors where it cannot load js files. i don't know how to correct my urls and it showed the following errors. i followed this tutorial https://levelup.gitconnected.com/full-stack-web-tutorial-django-react-js-jwt-auth-rest-bootstrap-pagination-b00ebf7866c1 i can run the webpage at localhost at raspberrypi. but having problem to deploy it. i give the info of urls.py. i also showed the settings.py content for staticfiles: i also showed the content for index.html: The "react_and_bootstrap.html" is at same directory where index.html located. i've run "python manage.py collectstatic" and the static folder is located at project directory as follows: Under "app" folder contains: Under "sales" folder contains: Under "static folder contains: This is my nginx configuration segment: i only showed the code involved with this project. i would like to setup a subnet called "my domain/sales/" but unsuccessful. The main problem is it can't load the static files where my urls setting got problem. and probably my nginx setting also got problem. Hope someone can guide me to solve this problem. Thanks. (if need more info, i can provide further). i deployed this django rest framework app using gunicorn, supervisor and nginx on raspberry pi. Thanks again. -
django horizontal stacked bar chart
I hope you're all doing great. I have been struggling to make a stacked horizontal bar chart here, I feel like I am not far off from the solution but I can't seem to find it. Bar Chart code: var ctx = document.getElementById("myBarChart"); total_value = parseInt(document.getElementById("total_value").textContent); var myBarChart = new Chart(ctx, { type: 'horizontalBar', indexAxis: 'y', data: { labels: [ {% for group in chart_group_data %} '{{group}}', {% endfor %}, ], datasets: [ {% for obj in timeperiod_list %} { label: "Value", stack: "Base", backgroundColor: [{% for obj in group_value %} '{{obj.timeperiod.color}}',{% endfor %}], hoverBackgroundColor: [{% for obj in group_value %} '{{obj.timeperiod.color}}',{% endfor %}], borderColor: [{% for obj in group_value %} '{{obj.timeperiod.color}}',{% endfor %}], data: [{% for obj in chart_percentage_data %} '{{obj|floatformat:"2"}}', {% endfor %}], }, {% endfor %}], }, options: { responsive:true, maintainAspectRatio:false, layout: { padding: { left: 10, right: 25, top: 25, bottom: 0 } }, legend: { display: false }, scales: { xAxes: [{ ticks: { autoSkip: false, beginAtZero: true } }], yAxes: [{ stacked:true, }] }, } }); views.py for i in group: group_value_data = GroupValue.objects.filter(group=i) group_value_first = group_value_data.first() group_value_last = group_value_data.last() chart_timeperiod = TimePeriod.objects.filter(competition=obj_id) for time in chart_timeperiod: try: week_group_value = group_value_data.get(timeperiod=time) chart_percentage_data.append(week_group_value.value) except: chart_percentage_data.append(0) … -
Celery task has disabled backend until another task (from a different app) is imported
I'm having a problem with celery, redis backend in a django environment. When I import a celery task from one file the backend is DisabledBackend, and any calls to delay() hang/block. However when I import a celery task from another file, the backend is RedisBackend and any calls to delay() work fine. The weird part is that after importing the second task, the backend of the first task changes to RedisBackend and then works fine. See example below: >>> from file1 import task1 >>> task1.backend <celery.backends.base.DisabledBackend object at 0x7f2bf3582470> >>> from file2 import task2 >>> task2.backend <celery.backends.redis.RedisBackend object at 0x7f2bf2bc7668> # And now the very weird bit, the backend of task1 now is correct >>> task1.backend <celery.backends.redis.RedisBackend object at 0x7f2bf2bc7668> Both tasks are defined using the following construct from celery import shared_task @shared_task def task1(): # Logic here from celery import shared_task @shared_task def task2(): # Logic here I can't seem to find any reason why this might happen. When I inspect the celery log I see both tasks registered. - ** ---------- [config] - ** ---------- .> app: *redacted* - ** ---------- .> transport: redis://localhost:6379// - ** ---------- .> results: redis://localhost:6379/ - *** --- * --- .> concurrency: 2 … -
Annotate: Pass parameter to Subquery
I have a queryset as follow: result = model_a.union(model_b) The result have these fields: (`user`, `date`) Is it possible pass date field to a Subquery as follow? result.annotate(amount = Subquery( Model_C.objects.filter( Q(model_c__date__lt=('_date') # <--- Pass date here ) .aggregate(Sum('amount'), 0))['amount'] ) output_field=IntegerField() )) According to the above implementation, the following error occurs: ... raise FieldError('Related Field got invalid lookup: {}'.format(lookup_name)) django.core.exceptions.FieldError: Related Field got invalid lookup: date_lt Is it possible to pass the fields from the result to Subquery in order to filtering? Is there another way? -
Django-rules makemigrations "No changes detected"
I'm using django-rules for object level security. I recently added a new field "managers" to my Location model, but python manage.py makemigrations doesn't detect it: No changes detected Given the following model: from django.db import models from django.conf import settings from django.contrib.auth.models import Group from rules.contrib.models import RulesModel # Create your models here. STATUS = [ ("red", "red"), ("amber", "amber"), ("green", "green"), ] class Location(RulesModel): name = models.CharField(max_length=200) description = models.TextField(blank=True) status = models.CharField(max_length=5, choices=STATUS, default="green") owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) managers = models.ForeignKey(Group, on_delete=models.SET_NULL, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) I red on https://izziswift.com/django-1-7-makemigrations-not-detecting-changes/ that makemigrations might not detect it because the Class doesn't inherit django.db.models.Model. Is there a way to get python manage.py makemigrations working as expected? -
Django form errors appearing without error
I made a research here in Stack and my problem is the opposite of the majority, I saw some ways to make it appear, but my problem is that it's appearing when the user hits the "Register" button / Refresh the register page. So it's an annoying thing that appears wherever the user enter/refresh the page because the form is empty. View.py @unauthenticated_user def register(request): form_u = CreateUser(request.POST) form_c = CreateClient(request.POST) if request.method == 'POST': form_u = CreateUser(request.POST) form_c = CreateClient(request.POST) if form_u.is_valid() and form_c.is_valid(): user = form_u.save() group = Group.objects.get(name='func') user.groups.add(group) client = form_c.save(commit=False) client.user = user client.save() return redirect('login') else: form_u = CreateUser() form_c = CreateClient() context = {'form_u': form_u, 'form_c': form_c} return render(request, 'register.html', context) HTML <form method="POST" action="" id="ativa"> {% csrf_token %} ... </form> {{form_u.errors}} {{form_c.errors}} <div class="mt-4"> <div class="d-flex justify-content-center links"> Have an account ? <a href="{% url 'login' %}" class="ml-2">Login</a> </div> </div> Print P.S: The site is in portuguese, but I can share the form link in heroku -
onw of my two app is not working in django
Below is my code. In my hello_world project there is two app pages. one is home page and another is profile page. home page is working fine, but profile page is showing error. hello_world urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('',include('home_page.urls',)), path('profile_page',include('profile_page.urls',)) ] home page urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('',views.home,name='home page'), ] home page views.py from django.http import HttpResponse def home(request): return HttpResponse('home page') profile page urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('profile_page',views.profile,name='profile page'), ] profile page views.py from django.http import HttpResponse def profile(request): return HttpResponse('profile page') -
Sorting using using href - Django
I am trying to sort the data by the column's header of a table. I am using the GET.get method but it seems that it doesn't work. The link is created but after i press it, the url changes but it the table is not sorted accordingly. def offer_sorting(request): sort_column = request.GET.get('sort_by', 'date') slist = Offer.objects.order_by(sort_column) context = {"offers": slist} return render(request, 'main/offer.html', context) the template: <!DOCTYPE html> <html> {% extends "main/header.html" %} {% block content %} <div class="row"> <div class="col-md"> <div> <h1> Offers </h1> <br> </div> <p align = "right"> <br> <a class="waves-effect waves-light btn-large" href = "submitoffer/">New Offer</a> </p> <div class="card card-body"> <table class="table"> <thead> <tr> <th><a href="{% url 'main:Offers' %}?sort_by=location_name">Location</a></th> <th>Date</th> <th>Minerals</th> <th>Chemical Analysis</th> <th>User</th> </tr> </thead> <tbody> {% for offer in offers %} <tr> <td>{{offer.location_name}}</td> <td>{{offer.date}}</td> <td>{{offer.minerals}}</td> <td>{{offer.chem_anal}}</td> <td>{{offer.user_data}}</td> <td> <a class="waves-effect waves-light btn" href = "{% url 'main:details' pk_test=offer.id %}" >Details</a> </td> <td> <a class="waves-effect waves-light btn" href = "{% url 'main:bid' pk_test=offer.id %}" >Bid</a> </td> </tr> {% endfor %} </tbody> </table> </div> </div> </div> {% endblock content %} </html> the model Offer includes the following fields which are going to be used for the sorting: minerals date location_name -
django filter one model with another model
I have two models and both have foreign keys with the User model. class UserCostCenter(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) cost_center = models.PositiveIntegerField() created_date = models.DateTimeField(auto_now_add=True) start_date = models.DateField(null=False, blank=False) end_date = models.DateField(null=True, blank=True) class UserBooking(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) date = models.DateField() hours = models.DecimalField() task = models.ForeignKey(UserProject, on_delete=models.DO_NOTHING, null=True, blank=True) created_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(null=True, blank=True) history = HistoricalRecords(table_name='booking_history_userbooking') Now I want to exclude the userbookings which does not have a cost center Currently I am doing like this: queryset = UserBooking.objects.all() for booking in queryset: cost_center = UserCostCenter.objects.filter( Q(user=booking.user, start_date__lte=booking.date, end_date__gte=booking.date) | Q(user=booking.user, start_date__lte=booking.date, end_date=None)).first() if not cost_center: booking_ids_without_cost_center.append(booking.id) queryset = queryset.exclude(id__in=booking_ids_without_cost_center) I do not want to exclude userbooking objects using for loop, please help! -
How to pass onclick variable from javascript to django form
I am a beginner and I really need your help for a function. You have a table and when you click on a cell, it opens a form in a pop-up modal to enter some text called "trigramme". Then you select the "time" (corresponding to the row) and the "position" (corresponding to the column) on the pop-up form, submit it and it will put the text into the correct cell on the table. This works correctly. Now, I would like to take the "time/position" variables directly from the cell clicked and pass these variables to the django form, so that you only have to enter the text in the form and submit it. I have a function to pick up the time and position after clicking a cell that works to display the cell clicked position (column header related to this cell) and time (row header related to this cell) : $('table').on('click', 'td:not(:first-child)', function(e) { var time = e.delegateTarget.tHead.rows[1].cells[this.cellIndex], position = this.parentNode.cells[0]; alert([$(position).text(), $(time).text()]); }) I also have this function to display the modal that works correctly : $(function () { var cells = document.querySelectorAll('td:not(:first-child)'); cells.forEach((e)=>{ e.addEventListener("click", ()=>{ $.ajax({ beforeSend: function () { $("#modal-activity").modal("show"); }, success: function (data) { $("#modal-activity.modal-content").html(data.html_form); … -
Django, multiprocessing and python logging
I have a django view with a method that calls multiprocessing.Process() and I'd like to configure logging to write logs to separate file for each subprocess. I've read some examples in the Python logging cookbook which focus on multiprocessing and writing logs to a single file, but I want to write to separate files. So I'm trying to create a new logging instance within the child process. I've set logging to None in django settings (because I think this is only called once in setup()) and then applied a logging config under the multiprocessed method, like so - def run_upgrade(self, input_data, status): logger = logging.getLogger("parent") logger.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # set the console handler ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) ch.setFormatter(formatter) logger.addHandler(ch) # set the filehandler fh = logging.FileHandler(f'/var/log/example/{status.device}.log') fh.setLevel(logging.DEBUG) fh.setFormatter(formatter) logger.addHandler(fh) Within the modules that are imported, I've then called getLogger(parent.child) to get them to propagate back to the root logger. Is this the right approach? -
Extendend Django App System to a "module" system?
honestly, I am not totally sure if thats a suitable SO question but I thought I can most likely get insights or answers here from the community. We currently devlop a web application or rather an extensible framework on top of django (Version 3.1.5). We therefore also use reusable apps but we lack several features of "plain" django apps: Some require changes to the settings.py We want to share a certain level of configuration (we use django-constance for that) Each app may (or may not) bring other depdencies either as pip dependencies or other django apps that would need to be installed I know that django has a pretty opiniated approach and tries to strictly isolate what an app does and what is "site specific" and belongs to the settings.py. In our scenario, however, both models don't perfectly fit as we want to have several deployments of a subset of our apps which we want to manage automatically and so, we dont want to manually maintan a large set of settings.py files that also are very similar and share lots of code (which is against Django very natural DRY). Finally, we came up with the idea of "modules" which are … -
Django: Adding more code or a new database table
I don't know if anyone has been in this situation before. I'm have a table named doctors, every doctor will have an attribute called universities where I will store the universities where the doctor studied. Anyway, should I add new table where I put the universities and link it to the doctors or should I store the universities in a text attributes in the doctors table and add some python code to analyse it when needed. Thanks in advance. -
How to check each key separately from a list in a loop without creating multiple loops. Which may have a KeyError etc
I wrote a code that takes 5 keys from API. The authors, isbn_one, isbn_two, thumbinail, page_count fields may not always be retrievable, and if any of them are missing, I would like it to be None. Unfortunately, if, or even nested, doesn't work. Because that leads to a lot of loops. I also tried try and except KeyError etc. because each key has a different error and it is not known which to assign none to. Here is an example of logic when a photo is missing: th = result['volumeInfo'].get('imageLinks') if th is not None: book_exists_thumbinail = { 'thumbinail': result['volumeInfo']['imageLinks']['thumbnail'] } dnew = {**book_data, **book_exists_thumbinail} book_import.append(dnew) else: book_exists_thumbinail_n = { 'thumbinail': None } dnew_none = {**book_data, **book_exists_thumbinail_n} book_import.append(dnew_none) When I use logic, you know when one condition is met, e.g. for thumbinail, the rest is not even checked. When I use try and except, it's similar. There's also an ISBN in the keys, but there's a list in the dictionary over there, and I need to use something like this: isbn_zer = result['volumeInfo']['industryIdentifiers'] dic = collections.defaultdict(list) for d in isbn_zer: for k, v in d.items(): dic[k].append(v) Output data: [{'type': 'ISBN_10', 'identifier': '8320717507'}, {'type': 'ISBN_13', 'identifier': '9788320717501'}] I don't know what … -
How to specify the SearchVector content manually in Django for Postgres?
Django supports the Postgres full-text-search using a SearchVectorField. The data has to be prepared using to_tsvector on the Postgres side which is done by the SearchVector function in Django: class SomeSearchableModel(PostgresModel): searchable = SearchVectorField() I need to populate this column with data not stored in other columns of the table. The default way to go would be: class SomeSearchableModel(PostgresModel): text = TextField() searchable = SearchVectorField() On every save: obj.searchable=SearchVector('text') # Column name to be read This application doesn't hold the searchable data in a usable format within the database. The content is prepared within some backend script. How do I provide the SearchVectorField content manually? Like: obj.searchable=SearchVector(some_processed_text) The PostgreSQL query part would be: INSERT INTO ... SET searchable=to_tsvector(...). Calculating the content in Postgres is no option. -
how to pass a data in a django view to other views without globall
so I am using a payment that has a view called verify , and It is going to check if the result was Ok , do something . But I need to pass order_id in the previous view that is token from the url to this view . some suggestion was using the global . but I am afraid of a error in the real server . If you need . Its the code : Previous view that sends a request to the payment center : def send_request(request , order_id): i = order_id amount = get_object_or_404(Order , id = i , user_id = request.user.id) result = client.service.PaymentRequest(MERCHANT , amount.total , description , email , mobile , CallbackURL) if result.Status == 100 : return redirect('https://www.zarinpal.com/pg/StarPay' + str(result.Authority)) else : return HttpResponse('error code : ' , str(result.Status)) And I need the order_id in the next view SO what can i do??Help please! -
my model field is not accepting "+" symbol into data. Using CharField field for model
models.py class Profile(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,null=True) mobile = models.CharField(max_length=14,null=True) add = models.CharField(max_length=10,null=True) image = models.FileField(null=True) def __str__(self): return self.user.username when i give mobile = +12345 its showing in admin as mobile = 12345 after i edit and save its showing +12345 why? and which field to use for including + symbol -
Querying users based on time
I want to add a class-based view to return users created from one date to another date. I have tried the following are there other ways to filter the user-created between two dates? views.py class RegisteredUserFilter(APIView): serializer = RegisteredUserFilterSerializer def get(self, from_date, to_date): userondate = User.objects.filter(created_at__range=[from_date, to_date]) return Response({"User": userondate}) serializers.py class RegisteredUserFilterSerializer(serializers.Serializer): from_date = serializers.DateField() to_date = serializers.DateField() model = User full code at: https://github.com/abinashkarki/rest_framework_authentication/tree/master/authapp