Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
List all video files from a usb storage device in Raspberry Pi as soon as the drive is plugged in
It should be similar to that Django Jquery file upload interface as in the link https://blueimp.github.io/jQuery-File-Upload/ except that the files should be listed automatically instead of uploading. I have no idea what to do or how to do it. Therefore I am asking you guys for help! Any help will be appreciated, Thanks, -
Reverse for 'cart_add' with arguments '('',)' not found. 1 pattern(s) tried: ['cart/add/(?P<book_id>[0-9]+)/$']
I was creating online library, when I had made my 'cart app' I got this error message Reverse for 'cart_add' with arguments '('',)' not found. 1 pattern(s) tried: ['cart/add/(?P[0-9]+)/$'] The main page(http://127.0.0.1:8000) is displayed normally As soon as I click the title of the book, that error appears. here is my cart app cord please save me pleas.......T_T from django.conf import settings from library.models import Book class Cart(object): def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def add(self, book, quantity=1, update_quantity=False): book_id = str(book.id) if book_id not in self.cart: self.cart[book_id] = {'quantity': 0} if update_quantity: self.cart[book_id]['quantity'] = quantity else: self.cart[book.id]['quantity'] += quantity self.save() def remove(self, book): book_id = str(book.id) if book_id in self.cart: del self.cart[book_id] self.save() def save(self): self.session[settings.CART_SESSION_ID] = self.cart self.session.modified = True def __iter__(self): book_ids = self.cart.keys() books = Book.objects.filter(id__in=book_ids) for book in books: self.cart[str(book.id)]['book'] = book def __len__(self): return sum(item['quantity'] for item in self.cart.values()) def clear(self): self.session[settings.CART_SESSION_ID] = {} self.session.modified = True from django import forms PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 21)] class CartAddProductForm(forms.Form): quantity = forms.TypedChoiceField(choices=PRODUCT_QUANTITY_CHOICES, coerce=int) update = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) from django.urls import path from . import views app_name … -
How can I serialize Django REST framework Serializers?
Maybe this isn't possible but given a Django Serializer class like this: class ExampleSerializer(serializers.Serializer): name = serializers.CharField(min_length=1, max_length=200) I'd like there to be a way for the client to get it like a JSON Schema like this (I don't particularly care about the format, OpenAPI would be okay too): { "$id": "https://example.com/example.schema.json", "$schema": "http://json-schema.org/draft-07/schema#", "title": "ExampleSerializer", "type": "object", "properties": { "name": { "type": "string", "minLength": 1, "maxLength": 200 } } } The advantage of this is that I don't have to duplicate the schema logic in the client too. I tried to use their CoreAPI which documents endpoints but it seems like in order to use it I'd need to convert all my serializers to use their AutoSchema format. I don't want to do because I already have it in the seralizer format. What's the recommended way to do this? If there isn't one (already asked on Reddit), it'd be relatively easy for me to create a Serializer-to-JSONSchema converter but I can't imagine I'm the first person to have wanted this. -
how can i add a background image to my website i am using python and django
how can i add a background image to my website? i am very new to programming and can someone pls tell me how can i add a background image i saw a few tutorials and talk about something like css and but i am confused can some pls help me.here is the code i have written please tell me what i can add to add a background image. index.html {% extends 'base.html' %} {% block content %} <h1>Products</h1> <div class="row"> {% for product in products %} <div class="col"> <div class="card" style="width: 18rem;"> <img src="{{ product.image_url }}" alt="..." width ="100%"> <div class="card-body"> <h5 class="card-title">{{ product.name }}</h5> <p class="card-text">{{ product.price }}₹</p> <a href="#" class="btn btn-primary">Add to cart</a> </div> </div> </div> {% endfor %} </div> {% endblock %} settings.py """ Django settings for pyshop project. Generated by 'django-admin startproject' using Django 3.0.4. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'fe#w(lb3nf8pqg0s0)9ux9r3_#c7v8p$28(qvtoko=l-ffjg8v' # … -
How to show Realtime data in a Django Webpage?
I am using Django to build a Webpage.I need to show my sensor values that is coming from an Esp32 board .which is connected to the same local network and Sends a message through TCP socket every 10 seconds,I need to collect this data and show this in Django Webpage,Could anyone help me with the code snippets to do so? -
Creating a downloadable Link with pk in Django
I've a code view which has a pk (primary key), when I click on the link in HTML, nothing seems to be working... Here's my code for easy understanding Views: ''' import mimetypes From wsgiref.util import Filewrapper def audio_download (request, pk): download =get_object_or_404(Audio,pk=pk) file =download.audio.audio.url.strip('/') wrapper = FileWrapper(open(file, 'rb')) response= HttpResponse(wrapper, content_type='application/force-download') response ['Content-Disposition]="attachment; filename="+os.path.basename(file) Print ('response') return response Then my url: ''' url (r'^audio/download/(P<pk>\d+)/$, views.audio_download, name= 'audio_download') Then lastly, HTML {%for audio in audio%} <a href = "audio/download/{{audio.id}}">{{audio.title}}</a></center> {%endfor%} -
How to render interactive Dash - Plotly using Django (REST framework)?
I'm currently working with generating dashboards. While I understand I can add plotly dash in django templates. I don't seems to understand to use it in a REST framework. I want to know if it is possible to return an 'url' to the front end and on accessing that url - the plotly dash is displayed. Any ideas on how to do this? -
save objects from views to another table drf
i am trying to save data in this table but i'm getting two field only and all the other i want to add manually models.py: class ProviderStatus(UUIDBase): provider_id = models.ForeignKey(Provider, to_field="uid", db_column='provider_id', verbose_name=_("Provider id"),on_delete=models.DO_NOTHING) created_by = models.ForeignKey(User, to_field="uid", db_column='created_by', verbose_name=_("created by"),on_delete=models.DO_NOTHING, null=True) remark = models.TextField(_("Remark"), blank=True, null=True) effective_date_from = models.DateField(_("Effective Date From"),auto_now_add=False,auto_now=False, null=True) effective_date_to = models.DateField(_("Effective Date To"), null=True) provider_status = models.ForeignKey(ProviderStatusChoice, to_field="key", null=True, blank=True, verbose_name=_("Status"), on_delete=models.DO_NOTHING) serializers.py: class ProviderStatusSerilaizer(serializers.ModelSerializer): class Meta: model = ProviderStatus fields= ('uid','provider_id','created_by','remark','effective_date_from','effective_date_to','provider_status') views.py: i have other view and inside that i'm getting output parent_success_obj from that i'm getting its uid and also getting status field and i want to save these fields in this table provider_id = parent_success_obj.uid provider_status = status and other fields i'm taking null or date.now() how should i proceed in views.py: if 'parent_success_obj.uid': serializer_obj = ProviderStatusSerilaizer(data=data) if serializer_obj.is_valid(): serializer_obj.save() else: return CustomeResponse(request=request, comment=FIELDS_NOT_VALID, data=json.dumps(serializer_obj.errors, cls=UUIDEncoder), status=status.HTTP_400_BAD_REQUEST, validate_errors=1) i'm saving this data inside same view -
Django filter date before deadline
I want to filter the date 5 days before the deadline in Django, I already have a query but not working. How can I solve this? django views def bdeadline(request): def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) dl = books.objects.filter(deadline = datetime.now().date() +timedelta(days=5)) return render(request, 'deadline.html',{'title':'Car - Deadline', 'dl':'dl'}) -
Could not able to extend user model using OneToOneField because of migrations not changes
I have model named Voter. I want to authenticate it using django authentication. So I added OneToOneField. I am using this tutorial. but when I add bellow line, applyed makemigrations and migrate and try to fetch Voter objects then it generate error user = models.OneToOneField(User, on_delete=models.CASCADE) Previously I thought that i had done something wrong with extending user. But reading other answers in stackoverflow now it seems that it is because of migration is not applying. Code model.py(partial) class Voter(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # this line map voter with user but it produce error serial_voter_id = models.AutoField(primary_key=True) voter_id = models.CharField(unique=True, max_length=10) voter_name = models.CharField(max_length=255) voter_constituency = models.ForeignKey(Constituency, models.DO_NOTHING, blank=True, null=True) username = models.CharField(unique=True, max_length=32) password = models.TextField() voter_address = models.CharField(max_length=255, blank=True, null=True) area = models.CharField(max_length=10, blank=True, null=True) city = models.CharField(max_length=10, blank=True, null=True) pincode = models.IntegerField(blank=True, null=True) adhar_no = models.BigIntegerField(unique=True) birth_date = models.DateField() age = models.IntegerField() fingerprint = models.TextField(blank=True, null=True) authenticity = models.CharField(max_length=3, blank=True, null=True) wallet_id = models.TextField() class Meta: managed = False db_table = 'voter' migration entry from migrations/0001_initial.py migrations.CreateModel( name='Voter', fields=[ ('serial_voter_id', models.AutoField(primary_key=True, serialize=False)), ('voter_id', models.CharField(max_length=10, unique=True)), ('voter_name', models.CharField(max_length=255)), ('username', models.CharField(max_length=32, unique=True)), ('password', models.TextField()), ('voter_address', models.CharField(blank=True, max_length=255, null=True)), ('area', models.CharField(blank=True, max_length=10, null=True)), ('city', models.CharField(blank=True, max_length=10, null=True)), ('pincode', models.IntegerField(blank=True, … -
Why does my form url pass the same primary key for all posts?
I have an HTML template where I list out posts one by one, and for some reason, Template: {% for post in posts %} ... <form class='bookmark-form' method='POST' action="{% url 'add_bookmark' post.pk %}" data-url='{{ request.build_absolute_uri|safe }}'> {% csrf_token %} <input type="text" value="{{post.pk}}" class="post-pk" hidden> <button type='submit'><img src="/img/bookmark.svg" alt=""></button> </form> ... {% endfor %} Javascript: $('.bookmark-form').submit(function(event){ event.preventDefault() var $formData = $('.post-pk').val() var postData = {csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), 'post-pk': $formData} var $thisURL = $('.bookmark-form').attr('data-url') || window.location.href var form_action = $('.bookmark-form').attr('action') console.log($formData) $.ajax({ method: "POST", url: form_action, data: postData, success: function (data) {console.log(data)}, error: function(data) {console.log("Something went wrong!");} }) return false; }) Views.py Add Bookmark Function def add_bookmark(request, pk): if request.method=='POST' and request.is_ajax(): post = Post.objects.get(pk=pk) print(pk) user = request.user user.bookmarks.add(post) user.save() print(user.bookmarks.all()) return JsonResponse({'result': 'ok'}) else: return JsonResponse({'result': 'nok'}) HTML Rendered Page: Regardless of which bookmark button I click on, I always get the same output in my terminal and console log. Terminal: 10 <QuerySet [<Post: Hogwarts, a History>, <Post: The Truth: My Parents are Dentists>, <Post: How to Organize Money: An Easy 10000 Steps>, <Post: Reallllllllly Old Post>, <Post: My First Serious Post>]> Console Log: 10 {'result': "ok"} where 10 is the primary key for the 'My First Serious Post' Post. I can't … -
How do I display the question field in the page where I have used Answers List View in Django?
I am creating a Questions Answers website like Quora using Django. I have created a ListView for questions on the home page and by clicking on a particular question I can see the question and all the answers to that question just like Quora. So for that I have created two models below: class Questions(models.Model): questions_asked = models.CharField(default='' , max_length = 250) date_asked=models.DateTimeField(default=timezone.now) author = models.ForeignKey(Profile , on_delete = models.CASCADE) #Profile is also a model I created but not putting it here as it is not necessary. It #has fields User,description,followers,image def get_absolute_url(self): return reverse('test Home') def __str__(self): if self.questions_asked[-1]!='?': return f'{self.questions_asked}?' else: return f'{self.questions_asked}' class Answers(models.Model): answer = models.CharField(default='No Answers yet' , max_length = 1000) date_answered = models.DateTimeField(default=timezone.now) question_answered = models.ForeignKey(Questions , on_delete = models.CASCADE) author = models.ForeignKey(Profile , on_delete = models.CASCADE) def get_absolute_url(self): return reverse('test quest detail' , kwargs={'pk':self.question_answered.pk}) def __str__(self): return f'{self.answer}' When a question is clicked I pass its primary key to the next url which displays the Answers. When the answers database has some answers I can print the question in tag on the HTML template as shown. This is the HTML template where I want to show the question clicked and the list of … -
Unable to define a ForeignKey field in Django models
I am not able to define ForeignKey relation from UsersGroups model with the other two models Roles and Users. It throws an error - Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/jeetpatel/Desktop/env/lib/python3.7/site-packages/django/db/models/fields/related.py", line 786, in __init__ to._meta.model_name AttributeError: type object 'Roles' has no attribute '_meta' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/opt/python/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/usr/local/opt/python/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Users/jeetpatel/Desktop/env/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/jeetpatel/Desktop/env/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Users/jeetpatel/Desktop/env/lib/python3.7/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/Users/jeetpatel/Desktop/env/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/Users/jeetpatel/Desktop/env/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/jeetpatel/Desktop/env/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/jeetpatel/Desktop/env/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/Users/jeetpatel/Desktop/env/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/local/opt/python/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/jeetpatel/Desktop/eitan-app/users_and_auth/models.py", line 31, in <module> class UsersGroups(): File "/Users/jeetpatel/Desktop/eitan-app/users_and_auth/models.py", … -
Not all HTML form inputs save from a previous page
I am making an e-commerce website where a user can post an order. Posting the order is done with a simple HTML form. After the user posts an order, they are sent to a confirmation page, where they have the option of going back to the order form to edit their order (this button is equivalent to the back button on a browser). All of the fields, except for the first two, are saved and already put into the form, and I cannot figure out why. I want all of the fields to be cached, and already put into the form when the user goes back. I have been googlig this for hours, but everyone seems to want to do the opposite of me :( If it helps, I'm using the django web-framework. Fields that don't save: <div class="row justify-content-center mt-3"> <div class="col-md-4"> <h5>Pick Up Address</h5> <input class="form-control" id="autocomplete" name = "pu_addy" onFocus="geolocate()" type="text" size = '40' required/> <div class = "invalid-feedback"> Please Choose a Pickup Address </div> </div> <div class="col-md-4"> <h5>Delivery Address</h5> <input class="form-control" id="autocomplete2" name = "del_addy" onFocus="geolocate()" type="text" size = '40' required/> <div class = "invalid-feedback"> Please Choose a Delivery Address </div> </div> </div> ex of field … -
Django Pytz timezone full names with GMT value
pytz provides a list of timezones in formats like America/Chicago, America/Los_Angeles, Asia/Kolkata or the tz abbreviation. I want the full name for timezones GMT value like the following (GMT-11:00) Pacific/Pago_Pago (GMT-07:00) America/Santa_Isabel -
Why I am getting the NoReverseMatch error and how can I solve it?
When It executes it show me a error like this "reverse for 'book' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P[0-9]+)/book$'] Views <form action="{% url 'book' flight.id %}" method="post"> Urls path('', views.index, name='index'), path('<int:flight_id>', views.flight, name='flight'), path('<int:flight_id>/book', views.book, name='book') Error NoReverseMatch at /1 Reverse for 'book' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P[0-9]+)/book$'] ` -
TemplateDoesNotExist at / tasks/list.html
I am following a tutorial on how to build a To Do App and for some reason It should change the title on the page to To Do as an <\h3> but its giving me an TemplateDoesNotExist at / tasks/list.html when I change it to return render(request, 'tasks/list.html'). I created a template folder and put my list.html on there, but the part of 'tasks/list.html' is highlighted so something is wrong with that file. -
ProgrammingError at /cart/address/ column order_useraddress.type does not exist
I am trying to create an eCommerce application. And for useraddress (Billing and shipping ) want something like below. Here have a model called Order and UserAddress , which is class Order(models.Model): cart = models.ForeignKey(Cart,on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered_total = models.PositiveIntegerField() shipping_price = models.PositiveIntegerField(default=0) ordered = models.BooleanField(default=False) billing_address = models.ForeignKey(UserAddress,related_name='billing_address',on_delete=models.CASCADE) shipping_address = models.ForeignKey(UserAddress,related_name='shipping_address',on_delete=models.CASCADE,default=None) and class UserAddress(models.Model): BILLING = 'billing' SHIPPING = 'shipping' ADDRESS_TYPE = ( (BILLING , 'Billing'), (SHIPPING, 'Shipping') ) user = models.ForeignKey(UserCheckout, on_delete=models.CASCADE) name = models.CharField(max_length=50) phone = models.CharField(max_length=21,null=True) street_address = models.CharField(max_length=50) home_address = models.CharField(max_length=50) type = models.CharField(max_length=100,choices=ADDRESS_TYPE) def __str__(self): return self.user def get_full_address(self): return '{0}, {1},{2}'.format(self.name ,self.user,self.phone ) And my View is class AddressFormView(FormView): form_class = AddressForm template_name = 'orders/address_select.html' def dispatch(self, request, *args, **kwargs): b_address, s_address = self.get_address() if not (b_address.exists() and s_address.exists()): messages.success(self.request, 'Please add an address before continuing') return redirect('add_address') # redirect before checkout return super(AddressFormView, self).dispatch(request, *args, **kwargs) def get_address(self, *args, **kwargs): user_checkout = self.request.session['user_checkout_id'] b_address = UserAddress.objects.filter( type=UserAddress.BILLING, user_id=user_checkout) s_address = UserAddress.objects.filter( type=UserAddress.SHIPPING, user_id=user_checkout) return b_address, s_address def get_form(self): form = super(AddressFormView, self).get_form() b_address, s_address = self.get_address() form.fields['billing_address'].queryset = b_address form.fields['shipping_address'].queryset = s_address return form def form_valid(self, form, *args, **kwargs): billing_address = form.cleaned_data['billing_address'] shipping_address = form.cleaned_data['shipping_address'] … -
How do you use Ajax with Django to submit a form without redirecting/refreshing, while also calling the views.py function?
I would like to create a system for bookmarking posts, where there would be a page of posts to scroll down, and if you like one in particular, you can click on a button to save it to your bookmarks. I've searched the entire day for a solution that allows me to save the post to the User's Bookmarks, while also not refreshing/redirecting, but I have only managed to find methods that solve one problem at a time, not both. I'm not interested in changing the template view itself, but rather just saving the data into the database. My Template Code: <form class='bookmark-form' method='POST' action="{% url 'add_bookmark' %}" data-url='{{ request.build_absolute_uri|safe }}'> {% csrf_token %} <input type="text" value="{{post.pk}}" name="post-pk" hidden> <button type='submit'><img src="/img/bookmark.svg" alt=""></button> </form> My Ajax Code: $('.bookmark-form').submit(function(event){ event.preventDefault() var postData = {csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),} var $formData = $(this).serialize() var $thisURL = $('.bookmark-form').attr('data-url') || window.location.href $.ajax({ method: "POST", url: $thisURL, data: postData, success: function (data) {console.log(data)}, error: function(data) {console.log("Something went wrong!");} }) return false; }) My Views.py Function to save the bookmark: def add_bookmark(request): if request.method=='POST': pk = request.POST.get('post-pk') post = Post.objects.get(pk=pk) user = request.user user.bookmarks.add(post) user.save() print(user.bookmarks.all()) return JsonResponse({'result': 'ok'}) else: return JsonResponse({'result': 'nok'}) The current result is that the page … -
Django Diplay Data leafleft
I am learning djnago , I would like to display an html page (in template forlder) into another html file by keeping {% extends 'base.html' %} which my template HTML that has my nav bar, CSS , javascritp.. the structure: App1=>templates=>App1=>map.html (is a map app html file) App1=>templates=>App1=>home.html Src=>templates=>base.html in home.html I would like to diplay map.html and all base.html elements (nav bar, CSS, javasript) Here is my base .html code : <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- semantic UI --> <!--Chart js--> <!-- jQuery --> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <title>skill-site | {% block title %} {% endblock title %}</title> </head> <body> {% include 'navbar.html' %} {% block scripts %} {% endblock scripts %} <div class="container ui"> {% block content %} {% endblock content %} </div> </body> </html> here is the code for home.html but it is not working: {% extends 'base.html' %} {% block title %}my map{% endblock title %} {% block content %} {% include './map.html' %} {% endblock content %} Thanks for your help -
Dango.urls.exceptions.NoReverseMatch: Reverse for 'app_list' with keyword arguments '{'app_label': ''}' not found. 1 pattern(s) tried
I am trying to send certain parameters from my views to a custom changelist.html, but I keep getting the error : django.urls.exceptions.NoReverseMatch: Reverse for 'app_list' with keyword arguments '{'app_label': ''}' not found. 1 pattern(s) tried I know the root cause of this is I cannot find all the variables needed to be passed by the changelist_view() which is why it is failing. I am not sure how to get this object cl : cl.opts|admin_urlname -
Django background task runner on server?
I'm trying to run a background task runner on the Django web server. I'm not that familiar with Django but I've done this with asp.net before. So essentially I have the html and JS send a post, which will be a file, usually a huge file, then Django will send back a hash for which to check the status of the file upload. The website will then have a processing bar that tells the user what percent is uploaded or if it has crashed. Is there a way to do this in Django? In C# there's things called delegates for this, where you can just check the status of the job, but the web server still receives requests, cause I want to site to keep pinging the server to get the status. -
How do I transfer test database to product database
I'm working on an Django project, and building and testing with a database on GCP. Its full of test data and kind of a mess. Now I want to release the app with a new and fresh another database. How do I migrate to the new database? with all those migrations/ folder? I don't want to delete the folder cause the development might continue. Data do not need to be preserved. It's test data only. Django version is 2.2; Python 3.7 Thank you. -
Django- insert image in password-reset email
I am implementing Django inbuilt functionality of the password reset. I have overridden the standard email template but I don't know how to include an image in that email template. I have tried the static thing but its giving me a plain text in the email. password_reset_email.html {% load static %} {% load i18n %}{% autoescape off %} {% blocktrans %}Hey, You're receiving this email because you requested a password reset for your user account at {{ site_name }}.{% endblocktrans %} {% trans "Please go to the following page and choose a new password:" %} {% block reset_link %} {{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} {% endblock %} {% trans "Your username, in case you've forgotten:" %} {{ user.get_username }} {% trans "Thanks for using our site!" %} {% blocktrans %}The {{ site_name }} team{% endblocktrans %} {% <img src="{% static 'img/IMG_2095.jpg' %}" alt="My image"> {% endautoescape %} Email which i received -
Most efficient way to query Django model by distinct groups and iterate over those subset queries
I am trying to iterate over all of the fields in my model by grouping them by the date_created field and iterating over each query. I have been able to do so but my method seems inefficient. Is there a better, cleaner way? data = model.objects.all() distinct_dates = data.values('date_created').distinct() for each_date in distinct_dates: data.filter(date_created=each_date['date_created']) The values of each_date would be each unique date associated with the model and that field