Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django returning old value for update User
I've created a simple on a settings page. It contains a few basic data such as First Name, Last Name (default Django User model) and then it links to a One to One model called Profile, which have more fields such as Address, City and State. I update it as follows in my views: def post(self, request): try: data = request.POST user_data = User.objects.get(id=request.user.id) first_name = data['first_name'] last_name = data['last_name'] phone = data['phone'] address = data['address'] address_two = data['address_two'] city = data['city'] state = data['state'] zip = data['zip'] country = data['country'] user_data.first_name = first_name user_data.last_name = last_name user_data.profile.phone = phone user_data.profile.address = address user_data.profile.address_two = address_two user_data.profile.state = state user_data.profile.city = city user_data.profile.zip = zip user_data.save() return render(request, 'pages/settings_profile.html', context={'success': "Settings updated"}) except Exception as e: print(e) print('error') return render(request, 'pages/settings_profile.html', context={'error':"Oops, an error occured saving your settings. If this keeps happening, please screenshot this and contact support."}) So this saves 100% fine.. however as the the page reloads after submitting, everything would be updated, except the first_name and last_name... but then when I refresh the page it then returns the new data. Why would the One to One fields update on my template on initial page load after saving, … -
Django: Default file serving doesn't work correctly
I'm trying to make a simple system which lets the users to change their profile pictures. So basically when the user uploads any new image the system works as it should, but I added a function which sets the default picture with: profile_pic = models.ImageField(null=True, blank=True, default='profile_pic1.png') When I create a new user I can see this view in the new user settings: After I upload the new image I can see this (The image is rendered correctly, I can see it displayed): This is the error: My settings.py MEDIA_ROOT = os.path.join(BASE_DIR, '') MEDIA_URL = '/images/' Also, I'm using nginx, and this is the line which I included, but I don't think that it's working. location /media/ { alias /home/interkodas/interkodas_web/images/; } -
Prevent multiple submits in django form - setAttribute disable to false is not triggered
I'm trying to prevent users from clicking the submit button more than once on a django form. My form looks like this: <form method="post" autocomplete="off" enctype="multipart/form-data" id="expense-form"> {% csrf_token %} {{form}} <button id="expense-submit-button" class="uk-button uk-button-secondary uk-button-small" type="submit"> <span id="spinner-payment-button" class="spinner-border spinner-border-sm spinner-js"></span> Submit </button> </form Then in a script tag on the same template I got this document.getElementById("expense-form").addEventListener('submit', functSubmit); function functSubmit(event) { var button = document.getElementById("expense-submit-button") var spinner = document.getElementById("spinner-payment-button") button.setAttribute("disabled", true) spinner.classList.remove("spinner-js"); } When I hit the submit button, the form saves as usual, but the "disabled" attribute is never applied and the user can still click "submit" multiple times which results in multiple records in my db. Why isn't the event listener triggered? The reason I need this is because I got a form that takes some time to process (a few seconds) and I just need to signal to the user that its actually working as expected. -
How do i change the logged out redirect page?
Im currently trying to finish my learning log app using python and django , but i keep having a small error(if i could call it that way) . Whenever i log out from the website i get redirected to the default django logged out page : I have created a logged_out.html file and its located in the same folder as botht the registration one and login . I think my mistake might be either in the *base.html file here: <li class = "nav-item"> <a class="nav-link" href="{% url 'users:logout' %}">Log Out</a> </li> or in the settings file if i have to include something that tells what to use . Thank you in advance. -
Cannot get recover password mails in Django using webmails.It sends mail from views.py but fails in sending password recovery mail
this works fine EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'myname@gmail.com' EMAIL_HOST_PASSWORD = '**********' this fails in sending password recovery mails but works fine while sending from views.py EMAIL_USE_TLS = True EMAIL_USE_SSL = False EMAIL_HOST = 'mail.mydomains.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'alert@mydomains.com' EMAIL_HOST_PASSWORD = '*************' -
how to capture and send image to Django using Ajax?
I'm trying to capture image from webcam using java-script and pass the same image to the Django. I've come to know that this would require ajax to work. But apparently form data is not passed to the Django. I've also tried to append image to form data but it won't work. Is there any way to make this work? Here's my Code <html> <body> <form method="post" enctype="multipart/form-data" id="uploadimage" data-toggle="validator"> <div class="form-group"> <!-- Stream video via webcam --> <video playsinline autoplay></video> <canvas id="canvas" width="600" height="450"></canvas> <img src="" id="detect-data" name="detect-data" width="600" height="450"> </div> <div class="form-group"> <button type="submit" id="submit" class="btn btn-lg">Next</button> </div> </form> <div class="clear"></div> <!-- js --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <!-- Script to capture image from webcam --> <script> const constraints = { video: true }; // create canvas const canvas = document.getElementById('canvas'); // get image const image = document.getElementById('detect-data'); // get capture button const captureVideoButton = document.getElementById('submit'); // get video element const video = document.querySelector('video'); navigator.mediaDevices.getUserMedia(constraints). then((stream) => { video.srcObject = stream }); captureVideoButton.onclick = function () { canvas.width = video.videoWidth; canvas.height = video.videoHeight; canvas.getContext('2d').drawImage(video, 0, 0); // Other browsers will fall back to image/png image.src = canvas.toDataURL('image/jpeg'); // call ajax function to pass data to django do_ajax(image) } function do_ajax(img) { … -
Django Application has become slow ever since I connected it to an online database
The app works perfectly fast and smooth if connected to an sqlite local db but is extremely slow when connected to postgresql/mongodb. -
how can I use something from a reusable app that is implemented in the main app in django?
I have a django app that is supposed to be used by different products, so it is a reusable app. This reusable app has DRE views, but for some views, I dont want to have always the same view permissions but instead I would like the final application (the product) to implement the view permission, because they can vary. For example: from rest_framework import permissions class MyCustomPermission(permissions.BasePermission): def has_permission(self, request, view): return finalAplicationPermission(request) if finalAplicationPermission else True and then use this custom permission in my view from rest_framework import generics from reusable_app import permissions class MyView(generics.GenericAPIView): permission_classes = (permissions.MyCustomPermission,) filterset_fields = ("somefield",) Any suggestion? Thanks in advance. -
Django-React Spotify Authentication with New User
I'm setting up a Django-React app and trying to allow users to login via Spotify which then takes them to a signup page to add username, bio, etc. or takes them to their profile page if they have already signed up. What's the best way to do this? I have been trying to use Django-allauth but having difficulty using this with React and not Django templates. Thanks. -
Url or Path inside urlpatterns in django
I am new to Django Api. While writing urls inside the app api url file, sometimes people use path and sometimes they use url in urlpatterns as shown below. And when they use path instead of url, they use routers just like below. I am totally cofused as to which one to use when?Plese help. This is path version. router = routers.DefaultRouter() router.register(r'user', views.UserCreateAPIView) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ path('', include(router.urls)), path('register', include('rest_framework.urls', namespace='rest_framework'))] This is url version. urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^products/$', views.product_list), url(r'^products/(?P<pk>[0-9]+)$', views.product_detail), ] -
Enviroment variables in pyenv-virtualenv
I have created a virtual environment with pyenv virtualenv 3.5.9 projectname for developing a django project. How can I set environment variables for my code to use? I tried to add the environment variable DATABASE_USER in /Users/developer/.pyenv/versions/projectname/bin/activate like this: export DATABASE_USER="dbuser" When I tried to echo $DATABASE_USER an empty string gets printed. Tried to install zsh-autoenv And now I can echo $DATABASE_USER and get the value set in the .autoenv.zsh file. But I can't seem to get the environment variable to be available to my django code: def getenv(key, default, prefix=''): try: return os.environ[prefix + key] except KeyError: if default is not None: return default else: raise ImproperlyConfigured('The {}{} environment variable must be set'.format(prefix, key)) If I try to getenv('DATABASE_USER', '') in the python shell inside the virtualenv, I get '' What could be wrong? Is the zsh-autoenv variables just available for the zsh shell and not python manage.py shell ? -
Redirect to previous url (update form filled in half)
In my app user is filling the form to update item. The are dropdown lists to choose from (foreign key relations) It there is no requested item on the list user can add his own item. He can do this using a separate modal form. (adding new item) After adding this new item I would like to redirect the user back to initial updating. I was trying to use hidden input: next = request.POST.get('next', '/') return HttpResponseRedirect(next) and return HttpResponseRedirect(request.META.get('HTTP_REFERER')) but I failed. My idea was to redirect the user to the previous URL: [![PREVIOUS URL][1]][1] views.py class NewSalesPersonDistributor(BSModalCreateView): template_name = 'newsalespersondistributor.html' form_class = NewSalesPersonDistributor success_url = "/VCI" def get_success_url(request): next = request.POST.get('next', '/') return HttpResponseRedirect(next) class VCIUpdateView(UpdateView): model = VCI context_object_name = 'VCIUpdate' form_class = VCIModelForm template_name = 'VCIupdate.html' success_url = "/VCI" urls.py path('VCIUpdate/<pk>', VCIUpdateView.as_view(), name='VCIUpdate'), path('createsalesperson/', NewSalesPersonDistributor.as_view(), name='new_sales_person_distibutor'), html div class="container"> <div class="row py-4"> <div class="col"> <form method="post" id="subsidiaryForm" name="text" data-subsidiaries-url="{% url 'ajax_load_subsiriaies' %}" data-salesPersonsDistributor-url="{% url 'ajax_load_salesPersonsDistributor' %}" data-salesPersonsDistributorContact-url="{% url 'ajax_load_salesPersonsDistributorContact' %}" novalidate> <table class="table table-borderless table-condensed"> {% csrf_token %} {{ form.as_table }} </table> <input type="hidden" name="next" value="{{ request.path }}"> <input type="hidden" name="build" value="{{ VCIUpdate }}">, <input id="submit" type="submit" value="save" /> </form> </div> <div class="col" id="filia" data-filia-url="{% url … -
Made a app and want to access its models in other apps and want to restrict user registration for accessing website
I am working on a django project , I am a beginner and thought that i should make a new app for user management so made it but now want to access the models of that app from other apps and also want to ensure that before accessing evry url of website the user has to login i have used UserCreatonForm and extended it. -
How to localize datetime in Django view code?
I have a datetime in "models.py": class Foo(models.Model): modified = models.DateTimeField() When I display this in a template it comes out correct i.e. according to my locale settings (I'm in British Summer Time): {{ foo.modified }} Settings: LANGUAGE_CODE = 'en-gb' TIME_ZONE = 'Europe/London' USE_I18N = True USE_L10N = True USE_TZ = True Correctly outputs what I'd expect "7 Sep 2020, 2:43 p.m." (printing "modified" in the view gives "2020-09-07 13:43:40.988953+00:00"). However when I try to copy this formatting to a string in the view I get the wrong date / time (it has not adjusted by one hour): from django.utils.formats import localize from app.models import Foo foo = get_object_or_404(Foo, pk=1) modified = localize(foo.modified, use_l10n=True) print(foo.modified) Outputs "7 Sep 2020, 1:43 p.m.", which is wrong. I tried the other answers on this thread and none outputted the adjusted datetime: Stack Overflow thread -
How to get the time to read a blog in Django?
In blogs, news articles, etc., there are these text that says x min read. I want to know how this is done. I know this seems very simple but I've tried searching for this on the internet unfortunately, I can't seem to find it. I've seen this somewhere before but I forgot the proper term for this. Can anyone help me out? Can anyone suggest a tutorial website/documentation/video for this? Thank you. -
Keycloak user Invitation email
I am using Keycloak-9.0.2 as SSO in my Django project. I want to get send an invitation link in the e-mail by one user to another user. Is there any inbuilt functionality in Keycloak for the same? If not then what should be the better way to do this in Django. -
How to implement markdown2 in the template tags? Getting TemplateSyntaxError 'md2' is not a registered tag library
I followed instructions at this source for getting markdown2 to work in the template tags. The code is below. settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'wikiencyc', 'markdown2', ] entry_detail.html {% load md2 %} <h4>{{ entry.subject }} </h4> <br><br> <p> {{ entry.content|markdown:"safe" }} </p> So, I have done everything according to book. I also made sure that markdown2.py is in the path. But I get the following error. TemplateSyntaxError at /wikiencyc/entry/9 'md2' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache i18n l10n log static tz What am I doing wrong? -
Django order by issue when used Q filter with multiple order by and distinct
I am working on a photos project where a user can Download or Like a photo (do other operations as well) . I have two models to track this information. Below are the models used (Postgres the database used). # Photo model stores photos # download_count, like_count is stored in the same model as well for easier querying class Photo(models.Model): name = models.CharField(max_length=100, null=True, blank=True) image = models.ForeignKey(Image, null=True, on_delete=models.CASCADE) download_count = models.IntegerField(default=0) like_count = models.IntegerField(default=0) views = GenericRelation( 'Stat', related_name='photo_view', related_query_name='photo_view', null=True, blank=True) downloads = GenericRelation( 'Stat', related_name='photo_download', related_query_name='photo_download', null=True, blank=True) # Stat has generic relationship with photos. So that it can store any stats information class Stat(models.Model): VIEW = 'V' DOWNLOAD = 'D' LIKE = 'L' STAT_TYPE = ( (VIEW, 'View'), (DOWNLOAD, 'Download'), (LIKE, 'Like'), ) user = models.ForeignKey( User, null=True, blank=True, on_delete=models.SET_NULL) content_type = models.ForeignKey( ContentType, on_delete=models.CASCADE, default=0) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() stat_type = models.CharField(max_length=2, choices=STAT_TYPE, default=VIEW) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) My requirement is fetch the Photos that are popular this week. The popularity score should consider the likes count, download count. I had written below query to get the popular photos this week which checks the likes or downloads created this week. … -
Import code works fine on local computer but gives error on aws
models.py from django.conf import settings from django.db import models from subject.models import Subject from core.utils import generate_file_name def file_upload_path(instance, filename): # File will be uploaded to MEDIA_ROOT / user_<id>/<filename> name = instance.slug + ".zip" file_path = generate_file_name() return 'project_{0}/{1}/{2}'.format(file_path, instance.slug, name) def image_upload_path(instance, filename): # File will be uploaded to MEDIA_ROOT / user_<id>/<filename> if instance.project_image1 == filename: filename = "image_1.png" elif instance.project_image2 == filename: filename = "image_2.png" elif instance.project_image3 == filename: filename = "image_3.png" return 'project_{0}/{1}'.format(instance.slug, filename) class Project(models.Model): """This is model for project""" project_name = models.CharField(max_length=50,) description = models.TextField() slug = models.SlugField() technologies = models.TextField() owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) price = models.DecimalField(max_digits=99, decimal_places=2) subject = models.ManyToManyField( Subject, related_name="projects") created = models.DateField(auto_now_add=True) project_image1 = models.ImageField(upload_to=image_upload_path) project_image2 = models.ImageField( blank=True, null=True, upload_to=image_upload_path) project_image3 = models.ImageField( blank=True, null=True, upload_to=image_upload_path) project_zip = models.FileField(upload_to=file_upload_path) def search_by_id(self, id): return self.objects.get(id=id) def search_by_slug(self, slug): return self.objects.get(slug=slug) views.py from rest_framework import viewsets, generics from rest_framework.parsers import FormParser, MultiPartParser, FileUploadParser from .models import Project from .serializers import ProjectSerializer, ProjectListSerializer from .permissions import IsOwnerOrReadOnly class ProjectCreateView(generics.CreateAPIView): parser_classes = (MultiPartParser, FormParser,) serializer_class = ProjectSerializer permission_classes = [IsOwnerOrReadOnly, ] def perform_create(self, serializer): serializer.save(owner=self.request.user) class ProjectListView(generics.ListAPIView): parser_classes = (FileUploadParser,) serializer_class = ProjectListSerializer queryset = Project.objects.all() class ProjectRetrieveView(generics.RetrieveAPIView): parser_classes = (FileUploadParser,) serializer_class = … -
Django admin StackedInline won't work in production
I'm having problems understanding why same code would work well locally but it won't work as expected when it's hosted on server. I use three OneToOneField connected to a model as following: class Order(models.Model): customer = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True, blank=True) order_date = models.DateTimeField(default=timezone.now, verbose_name='Data comenzii') ... class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, null=False, blank=False) product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True, blank=True, verbose_name='Produs') ... class InvoiceInfo(models.Model): CUSTOMER_TYPE_CHOICES = [ ('PF', 'Persoană fizică'), ('PJ', 'Persoană juridică'), ] order = models.OneToOneField(Order, on_delete=models.CASCADE, primary_key=True) customer_type = models.CharField(max_length=100, choices=CUSTOMER_TYPE_CHOICES, default='PF', verbose_name='Tip client') # Pers. fizica customer_firstname = models.CharField(max_length=100, blank=True, null=True, verbose_name='Prenume') customer_lastname = models.CharField(max_length=100, blank=True, null=True, verbose_name='Nume') class DeliveryInfo(models.Model): order = models.OneToOneField(Order, on_delete=models.CASCADE, primary_key=True) # contact person customer_firstname = models.CharField(max_length=100, blank=False, null=False, verbose_name='Prenume') customer_lastname = models.CharField(max_length=100, blank=False, null=False, verbose_name='Nume') Using admin manager as following: from .models import Order, OrderItem, InvoiceInfo, DeliveryInfo, PaymentMethodInfo class InvoiceInfoInline(admin.StackedInline): model = InvoiceInfo class DeliveryInfoInline(admin.StackedInline): model = DeliveryInfo class PaymentInfoInline(admin.StackedInline): model = PaymentMethodInfo class OrderItemInline(admin.StackedInline): model = OrderItem extra = 0 readonly_fields = ('product_link',) class OrderAdmin(admin.ModelAdmin): inlines = [ InvoiceInfoInline, DeliveryInfoInline, PaymentInfoInline, OrderItemInline, ] And locally it works fine and all fields are displayed properly. But in production the only field that is diplayed properly is OrderItemInline and other three are missing. … -
tag_model uninitialized in migrations
I have written Migration file for Django taggit to convert all the tags in lowercase into database but If I am trying to add new tag then I am getting the following error: AttributeError: type object 'InventoryProductTag' has no attribute 'tag_model' Code for tag in tags: if any(tag.isupper() for tag in tag.name): tag.name = tag.name.lower().strip() try: with transaction.atomic(): tag.save() except IntegrityError as ex: if (ex.__cause__.diag.constraint_name == "taggit_tag_name_key"): products = InventoryProduct.objects.filter(tags=tag) if products: for product in products: product.tags.add(tag.name) product.save() -
Why variables declared in settings.py are not visible in models.py if declared outside model class?
I have the following code in models.py from django.conf import settings from django.db import models SOME_VAR_FROM_SETTINGS = settings.FAS_BR_ROOT_SITE class FasSolution(models.Model): solution_id = models.CharField(max_length=64) doc_date = models.DateTimeField() title = models.TextField() @property def document_1_url(self) -> str: return self.title + SOME_VAR_FROM_SETTINGS For some reason, if SOME_VAR_FROM_SETTINGS is declared as it is in my code (i.e. at the the very begining of the models.py, not inside FasSolution class) - it becomes equal to None inside document_1_url property. However, in the reality its value is not None but some text string. What is interesing is that If I move SOME_VAR_FROM_SETTINGS declaration inside FasSolution class, then its value from settings.py becomes reachable (i.e. it becomes actual text string instead of None). Why does it happen? In other words, why variable declaration outside my model class makes it unreachable? -
I can't delete products
I've been coding in the framework django for two weeks and now I am learning to delete products. Here's the html code I've done: {% extends 'base.html' %} {% block content %} <form action = '.' method= 'POST'> {% csrf_token %} <h1>Do you want to delete the product "{{ object.title }}"?</h1> <p><input type= 'submit' value = 'Yes' /> <a href='../'>Cancel</a></p> </form> {% endblock %} And the function I've coded to delete the product def product_delete_view(request, my_id): obj = get_object_or_404(Product, id = my_id) if request.method == "POST": obj.delete() context = { 'object': obj } return render(request,"products/product_delete.html", context) Here's my url path: path('products/<int:my_id>/delete', product_delete_view, name= 'product-delete') However, my product doesn't get deleted. -
Django un Azure Webapp: Run command on deployment
I am deploying a Django app to Azure Webapp, which does everything automatically. I have set it up so when I push to a specific Github branch, it is deployed and everything works. If I have to run a migration, I must login via SSH and run it manually (which is not perfect but I can accept it). However, I need to use django-background-tasks, which needs to have a command running constantly listen for new tasks. I can't find a way to run this on every deployment. I found some documentation but most of it is for Node apps, it seems. For example, following some (oudated) tutoriales, I logged into {myapp}.scm.azurewebsites.net but I didnt find any "Download deployment scripts", which it seemed to be the proper way to do it. Is there a way to set up some commands to run on deployment (without changing my current setup of deploy directly from Github using Github actions)? Or I have to do it manually? -
Django Query whether the field is an m2m field and display the data
I have a modelclass like: class A (models.Model): name = models.CharField (max_length = 250) Bs = models.ManyToManyField ('B') Cs = models.ManyToManyField ('C') and a Formclass like: class AForm (forms.ModelForm): class meta: model = A fields = ['name', 'Bs'] labels = {'name': 'name', 'Bs': 'list of B', 'Cs': 'list of C'} now i want to show this on a website. The problem for me is the M2M field, I would like it to be like: https://i.stack.imgur.com/3KSpq.png represent. Therefore I would now have to query in the html whether it is a ModelMultipleChoiceField field is about adapting the presentation for me: {% for field in AForm %} {% if field.field == django.forms.models.ModelMultipleChoiceField %} blah {% else %} {{field}} {% endif %} {% endfor %} Unfortunately, I already fail when asked whether the current field is an m2m field. How can I do that? In addition, the M2M field currently only shows the ids? on? it says: B (1) B (2) B (3) B (4) B (5) B has a first and last name, however, it would be nicer if there: Firstname1 Lastname1 Firstname2 Lastname2 Firstname3 Lastname3 Firstname4 Lastname4 Firstname5 Lastname5