Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I access model fields linked to another model In Model.py?
I have following model Schedule, Booking and RoutePrice. Schedule Model: class Schedule(BaseModel): bus_company_route = models.ForeignKey(BusCompanyRoute, on_delete=models.PROTECT) bus = models.ForeignKey(Bus, on_delete=models.PROTECT) travel_date_time = models.DateTimeField() seat_discounted_price_for_travel_agent = AmountField(null=True, blank=True) seat_discounted_price_for_user = AmountField(null=True, blank=True) seat_discounted_price_for_foreigner = AmountField(null=True, blank=True) representative_name = models.CharField( max_length=20, null=True, blank=True ) seat_price_for_travel_agent = AmountField(null=True, blank=True) seat_price_for_user = AmountField(null=True, blank=True) seat_price_for_foreigner = AmountField(null=True, blank=True) And Schedule is Linked to BusCompany Route in Many to One Relation. So BusCompany route model is. class BusCompanyRoute(BaseModel): route = models.ForeignKey(Route, on_delete=models.PROTECT) shift = models.ForeignKey( Shift, null=True, blank=True, on_delete=models.PROTECT ) journey_length = models.TimeField(null=True) bus_company = models.ForeignKey(BusCompany, on_delete=models.PROTECT) and BusCompanyRoute is linked with Route Price in One to many Relation. RoutePrice Model is as. class RoutePrice(BaseModel): bus_company_route = models.ForeignKey(BusCompanyRoute, on_delete=models.PROTECT) bus_type = models.ForeignKey(Category, on_delete=models.PROTECT) seat_price_for_travel_agent = AmountField(null=True) seat_price_for_user = AmountField(null=True) seat_price_for_foreigner = AmountField(null=True, blank=True) Now I want to get seat_price_for_travel_agent in schedule 'save method()' From RoutePrice Model I have come upto here. How shall I get seat_price_for_travel_agent from RoutePrice in Schedule? def save(self, *args, **kwargs): seat_price_for_travel_agent = self.bus_company_route.routeprice_set Now I don't know how to proceed further. -
Responsive Rest api to find data type
I am trying to create List Create api to find Excel file data type and sheet name and number of rows. For this I have created a Model and serializer for file format, file path and file name to read excel using pandas. I have successfully get the data from user and stored to db. But I am stucking to post the output of datatype, sheetname and imported data. Request please give your suggestion. # views.py class FindDataTypeListCrtApi(ListCreateAPIView): queryset = FindDatatype.objects.all() serializer_class = FindDataTypeSerializer def find_datatype(self, *args, **kwargs): querylist = FileDatatype.objects.all() file_format = self.request.GET.get('filetype') file_dir = self.request.GET.get('filepath') file_name = self.request.GET.get('filename') HERE = os.path.abspath(os.path.dirname(__file__)) DATA_DIR = os.path.abspath(os.path.join(HERE, file_dir)) file_path = os.path.abspath(os.path.join(DATA_DIR, file_name)) if file_format == 'Excel': xl = pd.ExcelFile(file_data) sheet_name = xl.sheet_names data = pd.read_excel(file_data) data_type = data.dtypes return data_type elif file_format == 'CSV': data = pd.read_csv(file_data) data_type = data.dtypes return data_type elif file_format == 'JSON': data = pd.read_json(file_path) data_type = data.dtypes return data_type else: return "File Format Not Available...!" # Model.py class FindDatatype(models.Model): ftype = [('CSV','CSV'), ('Excel','Excel'), ('JSON','JSON')] filetype = models.CharField(max_length=10, choices=ftype, blank=True) filepath = models.CharField(max_length=250, blank=True) filename = models.CharField(max_length=50, blank=True) createdDate = models.DateTimeField(auto_now_add=True) # serializers.py class FindDataTypeSerializer(serializers.ModelSerializer): class Meta: model = FindDatatype fields = "__all__" I get following output … -
Store variables from original function to use in the celery task
I have a basic function in my views - def DoSomething(request): username = request.user.username email = request.user.email celery.delay() return render(request, "home.html") And then I want my celery task to send an email using the variables collected in the original function. I can't simply get the username and email from within the celery task as requests won't work. celery.py - @app.task(bind=True) def celery(self): send_mail( username, # subject 'my message here', # message myemail@myemail.com, # from email [email], #to email ) How can I pass these variables over as heroku won't let me push an import to the celery.py page but importing them? -
How to get data by status field in django rest framework
Actually I'm working on a project.I want to get data by status field which is created in models.py in Django rest framework. Here this is my scource code Models.py file class employee(models.Model): name = models.CharField(max_length=50) salary = models.IntegerField() phone = models.CharField(max_length=20) address = models.CharField(max_length=250) status = models.CharField(max_length=20) Views.py file class employeeviewset(viewsets.ModelViewSet): queryset = models.employee.objects.all() serializer_class = serializers.employeeserializer class employeebystatus(viewsets.ModelViewSet): def get(self, request, status): employee = models.employee.objects.filter(status=status) if employee: serializer = serializers.employeeserializer(employee, many=True) return Response(status=200, data=serializer.data) return Response(status=400, data={'Employee Not Found'}) Urls.pyfile router = routers.DefaultRouter() router.register('employee/<status>/', employeeviewset) How to get data by status field using queries can any one tell me the answer -
Django - Get objects from third model using foreignkey
I have Models. class M1(models.Model): .... class M2(models.Model): .... class M3(models.Model): n1 = models.ForeignKey( M1, related_name="M1_related", on_delete=models.CASCADE ) n2 = models.ForeignKey( M2, related_name="M2_related", on_delete=models.CASCADE ) In templates I have M1 object. Using it, I want to get all M2 objects related to M1 object. I tried {{M1_object.M1_related.n2.all}} but is blank. Doing {{M1_object.M1_related}} gives me M3.None I looked at these two questions 1 and 2. They are similar to mine but not helpful. -
Django/Digital Ocean space botocore.exceptions.ClientError: An error occurred () when calling the PutObject operation:
Hello I was following this tutorial: link and I got to the section of sending my static files to the DigitalOcean AWS3 space with boto3 and django-storages, however when I call the collectstatic function I get the following error. I am really with setting projects live: File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/django/AgnieseMinimarkt/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/django/AgnieseMinimarkt/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/django/AgnieseMinimarkt/env/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/home/django/AgnieseMinimarkt/env/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/home/django/AgnieseMinimarkt/env/lib/python3.8/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 194, in handle collected = self.collect() File "/home/django/AgnieseMinimarkt/env/lib/python3.8/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 118, in collect handler(path, prefixed_path, storage) File "/home/django/AgnieseMinimarkt/env/lib/python3.8/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 355, in copy_file self.storage.save(prefixed_path, source_file) File "/home/django/AgnieseMinimarkt/env/lib/python3.8/site-packages/django/core/files/storage.py", line 52, in save return self._save(name, content) File "/home/django/AgnieseMinimarkt/env/lib/python3.8/site-packages/storages/backends/s3boto3.py", line 447, in _save obj.upload_fileobj(content, ExtraArgs=params) File "/home/django/AgnieseMinimarkt/env/lib/python3.8/site-packages/boto3/s3/inject.py", line 619, in object_upload_fileobj return self.meta.client.upload_fileobj( File "/home/django/AgnieseMinimarkt/env/lib/python3.8/site-packages/boto3/s3/inject.py", line 539, in upload_fileobj return future.result() File "/home/django/AgnieseMinimarkt/env/lib/python3.8/site-packages/s3transfer/futures.py", line 106, in result return self._coordinator.result() File "/home/django/AgnieseMinimarkt/env/lib/python3.8/site-packages/s3transfer/futures.py", line 265, in result raise self._exception File "/home/django/AgnieseMinimarkt/env/lib/python3.8/site-packages/s3transfer/tasks.py", line 126, in __call__ return self._execute_main(kwargs) File "/home/django/AgnieseMinimarkt/env/lib/python3.8/site-packages/s3transfer/tasks.py", line 150, in _execute_main return_value = self._main(**kwargs) File "/home/django/AgnieseMinimarkt/env/lib/python3.8/site-packages/s3transfer/upload.py", line 692, in _main client.put_object(Bucket=bucket, Key=key, Body=body, **extra_args) File "/home/django/AgnieseMinimarkt/env/lib/python3.8/site-packages/botocore/client.py", line 357, in _api_call … -
How to filter web traffic on Google Analytics based on type of user login using Django Authorization
I have a website where I have three different login accounts on a Django site: admin, customers, and sellers. Right now, the traffic for all three accounts is being aggregated together on Google Analytics. Does anyone know how I can tag traffic from each of these accounts so I can filter on my Google Analytics account? My two guesses are: I render some type of profile name into the creation of the Google Analytics instance that would allow me to filter in Google Analytics: ga('create','UA-XXXXXXXX-X','{{ profile_type }}'); I create separate tracking IDs for each profile type and render those in depending on the account logged in. I don't necessarily want three different accounts on the Google Analytics side of things though, I just want to be able to filter between them. An example would be to insert this into the GA snipped when a user is logged in as an admin: ga('create','UA-{{admin_ga_tracking_code}}') Filtering by IP is not a solution because my admins and customers are all around the world and change. Thank you for any insight you can provide! -
how to share android(remote device) screen in web application using python?
We are developing fully controlled MDM(Mobile Device Management). Whenever an admin click on screen sharing then android(remote device) screen must be visible(remote access also may need in future) to an Admin. Admin functionalities developing in python using Django framework. how can I achieve this using python. Please suggest any other things to achieve this. Thanks -
Which of the following should I pay for to be able to create and deploy a commercial website?
I am planning to develop a website for city-wide commercial use. I am planning to use the following: FRONT-END (Atom Text Editor) -HTML -CSS -Javascript -jQuery -Bootstrap BACKEND -Python -Anaconda -Django -SQL Hosting -PythonAnywhere -GoDaddy Which of them should I pay for and how much will it cost me per year? And do you have any suggestions? Thanks in advance! -
Any efficient way to avoiding two forloops in django
Any better or efficient way to this in django {% for list1item in list1 %} {% for list2item in list2 %} {% if forloop.counter == forloop.parentloop.counter %} {{ list1item }} {{ list2item }} {% endif %} {% endfor %} {% endfor %} I want to do something like this, but not working. {% for list1item in list1 %} {% with forloop.counter as i %} {{ list2.i }} {% endwith %} {% endfor %} -
Paginator not displaying page numbers Django
I'm trying to use the paginator inbuild Django module so that the user can pass the pages. The problem is that I've configured everything as it should, but the pages numbers are not displaying. The place where it should have the numbers is entirely blank. Why can that due to? Home Shop Shop <section class="ftco-section bg-light"> <div class="container"> <div class="row"> <div class="col-md-8 col-lg-10 order-md-last"> {% for item in items %} <div class="row"> <div class="col-sm-12 col-md-12 col-lg-4 ftco-animate d-flex"> <div class="product d-flex flex-column"> <a href="{{ item.get_absolute_url }}" class="img-prod"><img class="img-fluid" src='{% static "images/product-1.png" %}' alt="Colorlib Template"> <div class="overlay"></div> </a> <div class="text py-3 pb-4 px-3"> <div class="d-flex"> <div class="cat"> <span>{{ item.get_category_display }}</span> </div> <div class="rating"> <p class="text-right mb-0"> <a href="#"><span class="ion-ios-star-outline"></span></a> <a href="#"><span class="ion-ios-star-outline"></span></a> <a href="#"><span class="ion-ios-star-outline"></span></a> <a href="#"><span class="ion-ios-star-outline"></span></a> <a href="#"><span class="ion-ios-star-outline"></span></a> </p> </div> </div> <h3><a href="{{ item.get_absolute_url }}">{{ item.title }}</a></h3> <div class="pricing"> {% if item.discount_price %} <p class="price"><span>${{ item.discount_price }}</span></p> {% else %} <p class="price"><span>${{ item.price }}</span></p> {% endif %} </div> <p class="bottom-area d-flex px-3"> <a href="{{ item.get_add_to_cart }}" class="add-to-cart text-center py-2 mr-1"><span>Add to cart <i class="ion-ios-add ml-1"></i></span></a> <a href="#" class="buy-now text-center py-2">Buy now<span><i class="ion-ios-cart ml-1"></i></span></a> </p> </div> </div> </div> {% endfor %} </div> <div class="row mt-5"> <div class="col text-center"> <div … -
django return all users not showing in template
I'm trying to return all users in a listView but nothing is being shown. I've looked at other questions similar to this but can't get it to work. Here is my views.py code: from django.shortcuts import render from django.http import HttpResponse from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.contrib.auth import get_user_model from django.contrib.auth.models import User from django.views.generic import ( ListView ) def users(request): context = { 'users': get_user_model().objects.all() } return render(request, 'user/user_lists.html', context) class UserListView(ListView): model = get_user_model() template_name = 'users/user_list.html' context_object_name = 'users' HTML file ("Your users" comes out fine): <h2>All users</h2> {{ users }} -
Django live reload for template and static files
Can someone please suggest a good library that enables automatic reload of my server (in development) upon updating any file (python, template or even static)? I am using docker for development and runserver_plus from django-extensions. I came across django-livesync, however, I was wondering if there is any better solution since this library is having some minor glitch. -
django:how to show StreamingHttpRespomse as a video?
My django project returns an HttpStreamingRespons that contains frames of a video: views.py @condition(etag_func=None) def broadcast(request): global current_user_cam cc = current_vudeo.update() print(type(cc)) resp = HttpResponse(cc) return render(rtsp) current_video.update() def update(): while True: yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + bytearray(self.frame) + b'\r\n') The response is generating, but how can I post this generated result in an HTML template ? -
Django Rest : AssertionError: Cannot combine a unique query with a non-unique query
I am trying to get a queryset with unique instances of a model project. when I try to combine multiple querysets with & operator like projects = (q1_projects & q2_projects & q3_projects) I get this error AssertionError: Cannot combine a unique query with a non-unique query. -
How do I get a specific timezone aware date in Django?
I'm creating a date() object like this pytz_timezone = pytz.timezone(specific_timezone) start = request.query_params.get("start") timestamp = datetime.fromisoformat(start).astimezone(pytz_timezone).date() but when using that for a query, it's apparently a naive object: RuntimeWarning: DateTimeField MyObject.timestamp received a naive datetime (2020-01-31 00:00:00) while time zone support is active. warnings.warn("DateTimeField %s.%s received a naive datetime " How do I create a timezone aware date() object? -
Create objects in multiple nested serializer in django
I have 3 models which are related to each other via ManytoMany relation like this: class DemandEvents(models.Model): date = models.DateTimeField(blank=True, null=True) quantity = models.IntegerField(default=0) class DemandFlows(models.Model): events = models.ManyToManyField(DemandEvents) flow = models.ForeignKey(Flow, on_delete=models.CASCADE) kit = models.ForeignKey(Kit, on_delete=models.CASCADE) monthly_quantity = models.IntegerField(default=0) class Demand(models.Model): demand_flows = models.ManyToManyField(DemandFlows) delivery_month = models.DateTimeField(blank=True, null=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) I am trying to create the serializers for this but keep getting confused how to handle the multi-level nesting Serializer.py class DemandEventsSerializer(serializers.ModelSerializer): class Meta: model = DemandEvents fields = "__all__" class DemandFlowsSerializer(serializers.ModelSerializer): class Meta: model = DemandFlows fields = "__all__" class DemandSerializer(serializers.ModelSerializer): demand_flows = DemandFlowsSerializer(many=True) class Meta: model = Demand fields = "__all__" def create(self, validated_data): items_objects = validated_data.pop('form_list', None) prdcts = [] for item in items_objects: i = DemandFlows.objects.create(**item) prdcts.append(i) instance = Demand.objects.create(**validated_data) instance.demand_flows.set(prdcts) return instance How do I add events data to this DemandFlows? -
How can I access the Twitter API in a Celery task?
I can't seem to access the Twitter auth within a celery task as request is not defined. If I use my own account variables the task will run fine but when asking for the authenticated users it errors. Can anyone help? views.py def like(request): liker.delay() return render(request, "home.html") Celery.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'AutoTweetLiker.settings') app = Celery('AutoTweetLiker') app.config_from_object('django.conf:settings') app.conf.update(BROKER_URL='*********', CELERY_RESULT_BACKEND='******') app.autodiscover_tasks() @app.task(bind=True) def liker(self): oauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) access_key = request.session['access_key_tw'] access_secret = request.session['access_secret_tw'] oauth.set_access_token(access_key, access_secret) api = tweepy.API(oauth) ....The rest of my function using Twitter API... -
Django change data used in template based on checkbox dynamically
I have a database table that contains sets which each have a unique code. These codes are either 3 or 4 characters long. Sets with codes that are 4 characters long represent extra data that is not really needed and by default I filter out these sets before sending the data to the template. However I would like it so the the user can click a checkbox and display those extra sets in the table on the template. To do this I just an Ajax request to the view to send whether the checkbox is checked or not, and then change the base set data. In the view I use an If statement to decides what data is returned. I have checked and the If statement is working, however the data in the template is not changing. js: function ShowExtraSets(e) { console.log(e.checked) $.ajax({ url: '', type: 'POST', data: { csrfmiddlewaretoken : csrf_token, showExtraSets : e.checked } }); } view: def sets_page(request): if 'showExtraSets' not in request.POST: set_list = Set.objects.extra(where=["CHAR_LENGTH(code) < 4"]).order_by('-releaseDate', 'name') elif request.POST['showExtraSets'] == 'true': set_list = Set.objects.order_by('-releaseDate', 'name') else: set_list = Set.objects.extra(where=["CHAR_LENGTH(code) < 4"]).order_by('-releaseDate', 'name') set_filter = SetFilter(request.GET, queryset=set_list) set_list = set_filter.qs ... -
Django serializer does not throw error for flawed validated data
I am running a django application and I have a simple class-based django-rest CreateView. My problem is that data actually gets created even though I sent flawed data. I am not entirely sure if that's expected behaviour, but I think it shouldn't be. View is simple: class ModelCreate(CreateAPIView): """Create instance""" serializer_class = ModelCreateSerializer queryset = ModelCreate.objects.all() In my serializer I am overwriting the create method for some custom behaviour and I am adding two write-only fields that I need for my data creation: class ModelCreate(serializers.ModelSerializer): """Serialize objects.""" field_extra1 = serializers.CharField(write_only=True, required=True) field_extra2 = serializers.CharField(write_only=True, required=True) class Meta: model = ModelCreate fields = ( "field_extra1", "field_extra2", "field3", "field4", "field5", "field6", "field7", ... ) def create(self, validated_data): """Create obj and relate to other model.""" field_extra1 = validated_data.pop("field_extra1") field_extra2 = validated_data.pop("field_extra2") obj = Model.objects.get(name=field_extra1) relation = obj.objects.filter(name=field_extra2)[0] validated_data["relation"] = relation result = ModelCreate.objects.create(**validated_data) return result My model has many optional fields. field_fk = models.ForeignKey( Model, on_delete=models.CASCADE, related_name="building_objects", ) field_m2m = models.ManyToManyField( Model, default=None, blank=True, ) field3 = models.CharField( max_length=120, null=True, blank=True, ) field4 = models.FloatField( null=True, blank=True, validators=[MinValueValidator(0.0)], ) field5 = models.FloatField( null=True, blank=True, validators=[MinValueValidator(0.0), MaxValueValidator(1.0)] ) field6 = models.FloatField( null=True, blank=True, validators=[MinValueValidator(0.0)], ) field7 = models.FloatField( null=True, blank=True, validators=[MinValueValidator(0.0)], ) Now what … -
Django Serializer subclass inheritance
I can't work out why I am unable to override a field in my Serializer parent class. Here is my model: class AccountHolder(base.BaseModel): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) Here is the parent serializer class: class AccountHolder(serializers.Serializer): name = serializers.SerializerMethodField() def get_name(self, holder): return holder.first_name + " " + holder.last_name And the subclass: class SubAccountHolder(Recipient): effective_from = serializers.SerializerMethodField() def get_effective_from(self, sub_holder): return sub_holder.periods.all() .order_by("-effective_from") .first() .effective_from But when I debug the code it is not even calling the method get_effective_from. What would be the correct way of doing this? -
Django Requests As A Client Side
I have a Django app, which that was working fine for a long time. And I have a request to another application (third party), it was working correctly. But suddenly it stopped and returns the following error. HTTPSConnectionPool(host='HOSTNAME', port=PORT): Max retries exceeded with url: /TO/URL/PATH/ (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f2d2bc42a20>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution')) but when I do telnet it works fine, it works fine when I do curl request. Please, anyone, have an idea? -
Chart.js conflicting with JQuery
Basically I am new to Chart.js but not new to web developing. I have tested lots of ways but it's just JQuery. Whenever I load the chart normally, I get "Chart is not defined" error by JQuery. If I remove JQuery from the site completely I get no error and I get the chart, but I need JQuery, any ideas? <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.min.js" integrity="sha512-SuxO9djzjML6b9w9/I07IWnLnQhgyYVSpHZx0JV97kGBfTIsUYlWflyuW4ypnvhBrslz1yJ3R+S14fdCWmSmSA==" crossorigin="anonymous"></script> <script> $(function () { var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } }); }); </script> <canvas id="myChart" width="400" height="400"></canvas> I used the standard graph … -
How to format time into readable format in Django
I have a send_sms function, but the date format from the message is too long and detailed. I want it to format from 2021-01-24 05:12:21.517854+00:00 into just (5:12PM, 24Jan2021) How can I do it? Thanks! def send_sms(request): z = Test.objects.latest('timestamp') numbers = Mobile.objects.all() message = (f'Test ({z.timestamp})') class Test(models.Model): timestamp = models.DateTimeField(auto_now_add=True) -
Reverse for 'deletedata' with keyword arguments '{'pk': 1}' not found. 1 pattern(s) tried: ['delete/<int:id>/']
I tried to look in other solutions. But it didn't help me out. Kindly look into this. my html code. <tbody> {% for st in stu %} <tr> <th scope="row">{{st.id}}</th> <td>{{st.name}}</td> <td>{{st.email}}</td> <td>{{st.role}}</td> <td> <a href="{}" class="btn btn-warning btn-sm">Edit</a> {% csrf_token %} <form action="{% url 'deletedata' pk = st.id %}" method = "POST" class="d-inline"> {% csrf_token %} <input type="submit" class="btn btn-danger" value="Delete"> </form> </td> </tr> {% endfor %} </tbody> </table> my views.py and urls.py code def delete_data(request,id): if request.method == 'POST': pi = User.objects.get(pk=id) pi.delete() return HttpResponseRedirect('/') urlpatterns=[ re_path('<int:id>/',views.update_data,name="updatedata") ]