Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: 'MetaDict' object has no attribute 'get_field' django_elasticsearch
I want to use elasticsearch within django app and send some data from model object to it but there is a problem with I am already using django-elasticsearch-dsl library. here`s my django_elasticsearch configuration: from django_elasticsearch_dsl import Document, fields from django_elasticsearch_dsl.registries import registry from core.models.src.errorLog import errorLog @registry.register_document class ErrorLogDocument(Document): class Index: name = 'errors' settings = { 'number_of_shards': 1, 'number_of_replicas': 0 } class Django: model = errorLog fields = [ 'time', 'date', 'error', 'place', ] but when I run my app I get this error and don`t know how to handle this: django_field = django_attr.model._meta.get_field(field_name) AttributeError: 'MetaDict' object has no attribute 'get_field' Can anyone help this???? Blockquote enter code here -
Navbar custom breakpoint not working - dropdown not displaying
I have a website made using Django and Django CMS, and am trying to implement a custom breakpoint for the navbar, as currently resizing the browser window makes the elements stack on top of each other before the navbar collapses. I've been able to implement a custom breakpoint of 1400px, but when using it, the menu dropdown glitches and doesn't display when the hamburger button is pressed. The line of code that both makes the breakpoint work, and the dropdown not display, is .navbar-collapse.collapse { display: none!important; }. I'm suspecting my nav tags might be in the wrong order. Here's my HTML and CSS: {% load cms_tags menu_tags sekizai_tags staticfiles snippet_tags %} {% render_block "css" %} <style> @media (max-width: 1400px) { .navbar-header { float: none; } .navbar-toggle { display: block !important; } .navbar-collapse { border-top: 1px solid transparent; box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1); } .navbar-collapse.collapse { display: none !important; } .navbar-nav { float: none !important; margin: 7.5px -15px; } .navbar-nav > li { float: none; } .navbar-nav > li > a { padding-top: 10px; padding-bottom: 10px; } } </style> <nav class="navbar fixed-top navbar-expand-xl navbar-dark bg-dark fixed-top"> <div class="container-fluid" style="margin-left:-20px;"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <i class="fa … -
__in filter only returning one value, show query through intermediate table
Noob at coding and need help. I am trying to render the view article by filtering through the model Spots. I have an intermediate table ArticleSpots to link the 2 tables Spots and Articles. In the views article I want to show only the spots that are linked to that specific article. My problem is that Spots.objects.filter(id__in=articleSpots) only shows the first one value and not all of the spots that are linked. What am I doing wrong here? views.py def article(request, slug): articles = get_object_or_404(Articles, slug=slug) article_id = articles.id articleSpots = ArticleSpots.objects.filter(article__id=article_id) spots = Spots.objects.filter(id__in=articleSpots) context = {"spots": spots, "articles": articles} template_name = "articletemplate.html" return render(request, template_name, context) models.py class ArticleSpots(models.Model): article = models.ForeignKey('Articles', models.DO_NOTHING) spot = models.ForeignKey('Spots', models.DO_NOTHING) class Meta: managed = True db_table = 'article_spots' verbose_name_plural = 'ArticleSpots' def __str__(self): return str(self.article) + ": " + str(self.spot) class Articles(models.Model): title = models.CharField(max_length=155) metatitle = models.CharField(max_length=155) slug = models.SlugField(unique=True, max_length=155) summary = models.TextField(blank=True, null=True) field_created = models.DateTimeField(db_column='_created', blank=True, null=True) field_updated = models.DateTimeField(db_column='_updated', blank=True, null=True) cover = models.ImageField(upload_to="cover", blank=True, default='logo-00-06.png') class Meta: managed = True db_table = 'articles' verbose_name_plural = 'Articles' def __str__(self): return str(self.id) + ": " + str(self.title) class Spots(models.Model): title = models.CharField(max_length=155) metatitle = models.CharField(max_length=155) slug = … -
Filter queryset accouring to related objects in django
I used django-guardian library, I want to create Manager to filter objects according to user permission. So for-example: from guardian.shortcuts import get_objects_for_user class WithUser(models.Manager): user_obj = None def assign_user(self,user_obj): self.user_obj = user_obj qs = super().get_queryset() ######################### # how I know if the current qs have related field and how to get related field managers. #??????????????? def get_queryset(self): qs = super().get_queryset() if self.user_obj: qs = get_objects_for_user(self.user_obj,"view_%s"%self.model.__name__.lower(),qs,accept_global_perms=False) return qs class A(models.Model): # the model fields objects = WithUser() class B(models.Model): # the model fields a = models.ForeignKey(A,on_delete=Model.CASCADE) objects = WithUser() class C(models.Model): # the model fields b = models.ForeignKey(B,on_delete=Model.CASCADE) objects = WithUser() How to filter C objects according to it's permission and permission of A,B. I want general rule to filter any model objects according to its permission and permission of its related objects. -
Download Sqlite database for backup in django
I have a site for deploying this site I will use image so I don't have access to the project file so I wanna know is there any way to download sqlite database for backup in django -
Run django application on Background with PM2
Hello i have a django application which runs smoothly with python3 manage.py runserver. But to run it all time i need to use any process manager or manually create a service. I want to run it with pm2. But problem occurs when i try to run the app with pm2 as a process. Below is my pm2 config file. { apps: [{ name: "lab", script: "/home/ubuntu/sample-django-app/manage.py", args: ["runserver", "0.0.0.0:8080"], exec_mode: "fork", instances: "1", wait_ready: true, autorestart: true, max_restarts: 5, interpreter : "/home/ubuntu/venv/bin/python3" }] } But the following error occurs raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Traceback (most recent call last): File "/home/ubuntu/sample-django-app/manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/ubuntu/sample-django-app/manage.py", line 22, in <module> main() File "/home/ubuntu/sample-django-app/manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? here I have installed Django and the app runs smoothly … -
how to register a user with a specific email address Django?
How do I register a user with a specific email address? def register(request): if request.method == "POST": username = request.POST["username"] email = request.POST.include["mail"] # Ensure password matches confirmation password = request.POST["password"] confirmation = request.POST["confirmation"] if password != confirmation: return render(request, "auctions/register.html", { "message": "Passwords must match." }) -
how to delete previous uploaded file when a new one gets uploaded using id
I have simple cv upload class for users to upload their resume. it works just fine but when they upload a newer one, the previous wont get deleted. this is my code: class ResumeDocument(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) cvfile = models.FileField(upload_to="documents", null=True, validators= [validate_file_extension]) def save(self, *args, **kwargs): try: this = ResumeDocument.objects.get(id=self.id) if this.cvfile != self.cvfile: this.cvfile.delete(save=False) except: pass super().save(*args, **kwargs) how can I reach the previous id? id = self.id - 1. something like that. this is my views: @login_required def pdf_resume(request): if request.method == 'POST': form = DocumentForm(request.POST,request.FILES) if form.is_valid(): form.instance.user = request.user form.save() return redirect('pdf_resume') if 'delete' in request.GET: return delete_item(ResumeDocument, request.GET['id']) else: form = DocumentForm() documents = ResumeDocument.objects.filter(user=request.user) context = { 'form':form, 'documents':documents, } return render(request, 'reg/pdf_resume.html', context) and this is also my HTML code: {% if documents %} {% for doc in documents %} {% if forloop.last %} <div class="existing-item antd-pro-pages-applicant-profile-partials-style-reviewList"> <div class="ant-divider ant-divider-horizontal ant-divider-with-text-center" role="separator"><span class="ant-divider-inner-text"> </span></div> <div class="btn-delete" data-id="{{doc.id}}" style="position: relative;"> <div style="position: absolute; padding: 0.5rem; top: -1.5rem; left: -0.5rem; display: flex; justify-content: center; align-items: center;"><a style="color: red;"></a></div> </div> <a href="{{ doc.cvfile.url }}">cv</a> </div> {% endif %} {% endfor %} {%endif%} -
what is scheme is better for react and django project
I'm going to do my first full-stack project, a website with react and django. Actually I saw a lot of schemes that you can use these two technologies together but I want to choose the best. So I brought these three schemes and I want to know your opinions about theme. Creating react apps inside every django apps and design and transfer and modify data using djangorestframework. Separating frontend and backend in the root and make one react app in frontend and one django project in backend and using djangorestframework for fetching data. There is one django project and there's one app in there named frontend that handles react app and also there's a django app named api to handle serializing and fetching data using djangorestframework. If you prefer another method, please tell your opinion. -
how to use modelformset_factory with ajax request - django
im trying submit a form with a modelformset which upload multiple images with ajax , but it only saves the parent form not model formset_factory ! here is what i tried .. const form = document.getElementById('post-form-add-booking') form.addEventListener("submit",submitHanler); function submitHanler(e){ e.preventDefault(); $.ajax({ type:'POST', url:"{% url 'booking:add_booking', data:$("#post-form-add-booking").serialize(), dataType:'json', mimeType:'multipart/form-data', success:successFunction, error:errorFunction, }) } $('#addImgButton').click(function(e) { var form_dex1 = $('#id_form-TOTAL_FORMS').val(); $('#images').append($('#imgformset').html().replace(/__prefix__/g,form_dex1)); $('#id_form-TOTAL_FORMS').val(parseInt(form_dex1) + 1); e.preventDefault(); }); <form method="POST" enctype="multipart/form-data"id="post-form-add-booking" class="mt-2 ">{% csrf_token %} <div id="form"> <div class="border border-gray-900 p-2 rounded-xl bg-gray-900 bg-opacity-25 pb-2 relative"> <div class="grid md:grid-cols-2 md:gap-5"> <div class="groupinput relative bglightpurple rounded-xl"> <label class="text-white absolute top-1 mt-1 mr-2 text-xs">{% trans "room number" %}</label> <p class="w-full pr-2 pb-1 pt-6 bg-transparent focus:outline-none text-white">{{room_number.room_no}}</p> </div> <div class="groupinput relative bglightpurple rounded-xl"> <label class="text-white absolute top-1 mt-1 mr-2 text-xs">{% trans "address" %}</label> {{form.address | add_class:'w-full pr-2 pt-6 pb-1 bg-transparent focus:outline-none text-white'}} {% if form.address.errors %} <p class="text-white pb-2 pr-2 rounded-xl w-full">{{form.address.errors}}</p> {% endif %} </div> </div> <div class="grid md:grid-cols-2 md:gap-5"> <div class="groupinput relative bglightpurple mt-2 rounded-xl"> <label class="text-white absolute top-1 mt-1 mr-2 text-xs">{% trans "takes by" %}</label> {{form.taker | add_class:'w-full pr-2 pt-6 pb-1 bg-transparent focus:outline-none text-white'}} {% if form.taker.errors %} <p class="text-white pb-2 pr-2 rounded-xl w-full">{{form.taker.errors}}</p> {% endif %} {% if form.errors %} <p class="text-white pb-2 … -
Use Bootstrap by link or install in enviroment (pip install django-bootstrap3) in Django
I'm newbie of Django. I just find out there is 2 ways of loading bootstrap in Django with: 1. <link rel="stylesheet" href="" crossorigin="anonymous">: For CDN or local file. 2. Installing in enviroment with (pip install django-bootstrap3): Loading by {% load bootstrap3 %} Which way do you prefer in this case? Thank you so much. -
unsupported operand type(s) for -: 'decimal.Decimal' and 'float' | Django
Sometimes it works fine and sometimes it displays the error. ADMIN models.py class BarterAdminWallet(models.Model): admin_wallet_id = models.BigAutoField(primary_key=True) admin_wallet_balance = models.DecimalField(max_digits=60, decimal_places=2, default = 0.00) admin_tokens_assigned = models.DecimalField(max_digits=60, decimal_places=2, default = 0.00) admin_tokens_earned = models.DecimalField(max_digits=60, decimal_places=2, default = 0.00) admin_tokens_bought = models.DecimalField(max_digits=60, decimal_places=2, default = 0.00) class BarterAdminActionsTokens(models.Model): action_tokens_id = models.BigAutoField(primary_key=True) account_activation_tokens = models.DecimalField(max_digits=30, decimal_places=2, default = 0.00) newsletter_subscription_tokens = models.DecimalField(max_digits=30, decimal_places=2, default = 0.00) name_tokens = models.DecimalField(max_digits=30, decimal_places=2, default = 0.00) surname_tokens = models.DecimalField(max_digits=30, decimal_places=2, default = 0.00) add_languages_tokens = models.DecimalField(max_digits=30, decimal_places=2, default = 0.00) mobile_phone_tokens = models.DecimalField(max_digits=30, decimal_places=2, default = 0.00) avatar_image_tokens = models.DecimalField(max_digits=30, decimal_places=2, default = 0.00) profile_description_tokens = models.DecimalField(max_digits=30, decimal_places=2, default = 0.00) dob_tokens = models.DecimalField(max_digits=30, decimal_places=2, default = 0.00) linkedin_profile_tokens = models.DecimalField(max_digits=30, decimal_places=2, default = 0.00) facebook_profile_tokens = models.DecimalField(max_digits=30, decimal_places=2, default = 0.00) address_1_tokens = models.DecimalField(max_digits=30, decimal_places=2, default = 0.00) address_2_tokens = models.DecimalField(max_digits=30, decimal_places=2, default = 0.00) USER views.py adminwallet = BarterAdminActionsTokens.objects.get() registration_tokens = adminwallet.account_activation_tokens adminwallet = BarterAdminWallet.objects.get() adminwallet.admin_wallet_balance = adminwallet.admin_wallet_balance - float(registration_tokens) adminwallet.admin_tokens_assigned = adminwallet.admin_tokens_assigned + float(registration_tokens) adminwallet.save() token_status.user_account_activation_token_status = "Awarded" token_status.save() CODE EXPLANATION All fields related to maths are of the decimal. Same code, When calculating sometimes calculates perfectly and show error on some occasion. Also this code is working absolutely fine in other … -
Is this possible: Django TestCase + async + db calls?
I have a problem when use db calls in async methods of Django TestCase. I have an error: "psycopg2.InterfaceError: connection already closed". I know that I can use TransactionTestCase, but it's slow. Is there solution for this using Django TestCase? -
Django Rest Frame work, "Method \"GET\" not allowed.", but in the code, POST is requested
I was watching a tutorial to create a web app, using React in frontend and Django in backend therefore using Django Rest Framework I copied everything and even my code looked the same, but I am getting this HTTP 405 status and prompting that GET method is not allowed, I know it's not allowed because I haven't requested GET method, I requested POST method Here's my views.py : from django.shortcuts import render from rest_framework import generics, status from .serializers import RoomSerializer, CreateRoomSerializer from .models import Room from rest_framework.views import APIView from rest_framework.response import Response class RoomView(generics.ListAPIView): queryset = Room.objects.all() serializer_class = RoomSerializer class CreateRoomView(APIView): serailizer_class = CreateRoomSerializer def post(self, request, format=None): if not self.request.session.exists(self.request.session.session_key): self.request.session.create() serializer = self.serailizer_class(data=request.data) if serializer.is_valid(): guest_can_pause = serializer.data.get('guest_can_pause') votes_to_skip = serializer.data.get('votes_to_skip') host = self.request.session.session_key queryset = Room.objects.filter(host=host) if queryset.exists(): room = queryset[0] room.guest_can_pause = guest_can_pause room.votes_to_skip = votes_to_skip room.save(update_fields=['guest_can_pause', 'votes_to_skip']) return Response(RoomSerializer(room).data, status=status.HTTP_200_OK) else: room = Room(host=host, guest_can_pause=guest_can_pause, votes_to_skip=votes_to_skip) room.save() return Response(RoomSerializer(room).data, status=status.HTTP_201_CREATED) return Response({'Bad Request': 'Invalid data...'}, status=status.HTTP_400_BAD_REQUEST) And here's my urls.py : from django.urls import path from .views import RoomView, CreateRoomView urlpatterns = [ path('room', RoomView.as_view()), path('create-room', CreateRoomView.as_view()), ] I read somewhere that it has something to do with the URL so here's … -
DsTProductAttributes.product must be a DsTProductCompany instance Django
this would be my first post ever on Stack Overflow, I am asking a question that apparently has been already answered but I can't find the solution for my specific case. I am a beginner in Django so please don't be too hard. Thank you very much in advance even for reading my post. Any advice or directions will be highly appreciated. A. I am getting this error: Cannot assign "2": "DsTProductAttributes.product" must be a "DsTProductCompany" instance. Here is the relevant code from models.py class DsTProductAttributes(models.Model): product_attribute_id = models.BigAutoField(primary_key=True) product = models.ForeignKey('DsTProductCompany', models.DO_NOTHING) attribute = models.ForeignKey(DsTAttribute, models.DO_NOTHING) value = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) dw_load = models.DateTimeField(blank=True, null=True) dw_deleted = models.IntegerField(blank=True, null=True) dw_deleted_time = models.DateTimeField(blank=True, null=True) dw_last_touch = models.DateTimeField(blank=True, null=True) dw_last_touch_by = models.CharField(max_length=200, blank=True, null=True) class Meta: managed = False db_table = 'ds_t_product_attributes' class DsTProductCompany(models.Model): product_id = models.BigAutoField(primary_key=True) product_code = models.CharField(max_length=200, blank=True, null=True) description = models.CharField(max_length=200, blank=True, null=True) ean_code = models.CharField(max_length=200, blank=True, null=True) dw_load = models.DateTimeField(blank=True, null=True) dw_deleted = models.IntegerField(blank=True, null=True) dw_deleted_time = models.DateTimeField(blank=True, null=True) dw_last_touch = models.DateTimeField(blank=True, null=True) dw_last_touch_by = models.CharField(max_length=200, blank=True, null=True) class Meta: managed = False db_table = 'ds_t_product_company' Here is the relevant code from forms.py class ProductAttributesForm(ModelForm): def __init__(self, *args, **kwargs): super(ProductAttributesForm, self).__init__(*args, **kwargs) attribute = DsTAttribute.objects.all() … -
Django model UniqueConstraint problem, I want category parent not to be the current instance
Hey i have problem with the categories parent. As you can see in the code i have category with a foreign key pointing to it self. Now i dont want a instance of category to be a child of itself. So far i have tried unique_together and UniqueConstraint but that didn't work. class Category(models.Model): parent = models.ForeignKey('self', related_name="children", on_delete=models.CASCADE, blank=True, null=True) #'self' to indicate a self-reference. title = models.CharField(max_length=100) slug = AutoSlugField(populate_from='title', unique=True, null=False, editable=True) logo = models.ImageField(upload_to="catlogo", blank=True, null=True, help_text='Optional') created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Meta: #enforcing that there can not be two categories under a parent with same slug verbose_name_plural = "categories" constraints = [ models.UniqueConstraint(fields=['slug', 'parent'], name='unique_parent') ] -
Css file not loading on Python Anywhere
I have recently begun making a Django project on PythonAnyhwere. I have followed the entire tutorial provided by Django for including static files on the project. I have observed the programs work fine on a site with http, but does not work on a site with https. What could be the reasons and how can I overcome this problem? -
This backend doesn't support absolute paths
please I need urgent help on this: I am having This backend doesn't support absolute paths when trying the login. bellow is my codes models.py from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') role = models.CharField(default='user', max_length=20) def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.width > 280 or img.height > 280: output_size = (280, 280) img.thumbnail(output_size) img.save(self.image.path) settings.py STATICFILES_DIRS = [ BASE_DIR / "static", ] STATIC_ROOT = BASE_DIR / "staticfiles-cdn" # in production, we want cdn MEDIA_ROOT = BASE_DIR / "staticfiles-cdn" / "media" from .cdn.conf import * # noqa in django-project folder>cdn i have backends.py from django.conf import settings from storages.backends.s3boto3 import S3Boto3Storage class StaticRootS3Boto3Storage(S3Boto3Storage): location = 'static' class MediaRootS3Boto3Storage(S3Boto3Storage): location = 'media' conf.py import os AWS_ACCESS_KEY_ID=os.environ.get("AWS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY=os.environ.get("AWS_SECRET_ACCESS_KEY") AWS_STORAGE_BUCKET_NAME=os.environ.get("AWS_STORAGE_BUCKET_NAME") AWS_S3_ENDPOINT_URL="my digitalocean endpoint" AWS_S3_OBJECT_PARAMETERS = { "CacheControl": "max-age=86400" } AWS_LOCATION = "https://{AWS_STORAGE_BUCKET_NAME}.fra1.digitaloceanspaces.com" DEFAULT_FILE_STORAGE = "appname.cdn.backends.MediaRootS3Boto3Storage" STATICFILES_STORAGE = "appname.cdn.backends.StaticRootS3Boto3Storage" Thank you -
How to undo changes in a model in Django-oscar
I tried adding a field in AbstractProduct model and in doing so, I was successful, but now that field is being presented whenever I go to product detail view as an empty field and which is not desirable. and in the following image the state of the origin is the issue which I am facing..which can't be left blank so no one can place order.. How to solve this ?? -
reduce the time complexity of the this Django queryset parse function
This function takes a Django QuerySet table, fields (the column names of the table as a list), and a name (string). It checks to see if the name is in the column fields. if the name is in the fields, it will add the sum of the field to a list of sums and return that list as a dictionary after enumerating it. I noticed that it's running in o(n^2) (I think) and would like to reduce its time complexity. #returns an enumerated dict of sums of the fields in the table #table is a Django QuerySet, fields is a list of fields, name is a string def fieldSum_to_list(table, fields, name) -> dict: sum = [] name = name.lower() for field in fields: if name in field.name: if (None in table.aggregate(Sum(field.name)).values()): # value = 0 # sum.append(value) -> what I was doing before pass pass else: col_sum = table.aggregate(Sum(field.name)).get( str(field.name) + '__sum') sum.append(col_sum) diction = dict(enumerate(sum)) if (len(diction) == 1): return diction[0] return dict(enumerate(sum)) The program slowed down after adding this line: if (None in table.aggregate(Sum(field.name)).values()): is what slowed down the program as it was much faster before, I think that this condition is acting as a loop. In essence, … -
response returning null for no reason rest framework
I getting null in return when in fact i have data in the database, I don't where the problem lies, pretty frustrated by this, if I am not calling is_valid then it throws an assertion error but anyways data is still empty class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' View @api_view(['GET']) def get_data(request): product_data = Product.objects.all() print(product_data) serialized_data = ProductSerializer(data = product_data, many =True) data = {} if serialized_data.is_valid(): data['status']='valid' else: data['status']='not valid' return Response(data) -
Issue with trying to upload single images across multiple different HTML form inputs in Django without Django Forms
I am trying to create digital business cards creating a custom visual editor with different html form inputs to upload different images like profile, background, logo etc., without Django Forms. I am able to get one working with the Django backend that uses to fields one for the image name and the other is image url. I was hoping to replicate this process for each image until I get to the slider section. I am still working on it so the design is not complete and using test data. I have included an image for reference of what I am trying to accomplish as silly as the test data is on there. urls.py from django.conf.urls import url from django.urls import path from . import views urlpatterns = [ url(r'^icards/icard/list/$', views.icard_list, name='icard_list'), url(r'^icards/icard/add/', views.icard_add, name='icard_add'), url(r'^icards/icard/edit/(?P<pk>\d+)/$', views.icard_edit, name='icard_edit'), # url(r'^icards/icard_details/(?P<pk>\d+)/$', views.icard_details, name='icard_details'), url(r'^icards/icard/delete/(?P<pk>\d+)/$', views.icard_delete, name='icard_delete'), # url(r'^icards/editor_base/', views.editor_base, name='editor_base'), url(r'icards/', views.icards, name='icards'), views.py def icard_edit(request, pk): print("Icard Edit Loaded") if len(Icard.objects.filter(pk=pk)) == 0: error = "Icard Not Found" return render(request, 'back/error.html', {'error': error}) icard = Icard.objects.get(pk=pk) print("Icard get function works") if request.method == 'POST': print("func: Get Data Works") name = request.POST.get('name') category = request.POST.get('category') style = request.POST.get('style') title = request.POST.get('title') logo … -
How to change the default labels of a ForeignKey field whose form's widget is a RadioSelect
In my Django app, I have this form: from django import forms from main.models import Profile class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['picture'] widgets = { 'picture': forms.RadioSelect(), } By default, the labels of the picture field within the template are generated according to the __str__() method of the Picture model. That's because the picture field on my Profile model is actually a ForeignKey field to a Picture model. However, the value returned by that __str__() method doesn't make much sense in this particular template, and changing it is not possible because it's being used elsewhere. Therefore, is there a way I might change the default labels for the picture field of my ProfileForm? For instance, changing from the __str__()'s default picture.src + ' (' + picture.description + ')' to something like picture.description only? I have checked what the docs had to say regarding the label_from_instance, but I didn't understand how to apply it. In fact, I couldn't even understand if that would be a solution for this case. Some similiar questions here on Stack Overflow also mentioned that link of the docs, but the questions's forms were slightly different than mine, and I ended up not … -
I'm get a report of error ') expected' in django
I have a django website, and in my html I get these in my visual studio editor, I don't know why. Basically everything works, but I have some problem with flex, sometimes it doesn't work, also I don't know if it is connected. Any idea what is this? This is home.html <section class="welcome_area clearfix" id="home" style="background-image: url({% static 'img/bg-img/welcome-bg.png' %})"> Same in base.html <div class="mosh-breadcumb-area" style="background-image: url({% static 'img/core-img/breadcumb.png' %})"> -
Django-allauth Password Reset Email not sending
I have a weird problem where my allauth email will send to verify new user email address but no email will send for resetting the password. I have checked the gmail account from which the email should be sent but it only shows the verification emails as sent, its as though nothing is being done when the user clicks the reset password button on the template side. I'm not sure what I am missing.. My template <body class="login-page container-fluid"> <div class="row vygr-login"> <div class="user_card"> <div class="container-fluid h-100"> <div class="row h-100"> <div class="form_container col vygr-signup-container"> {% load i18n %} <form class="signup" method="POST" action="{% url 'account_login' %}"> {% if user.is_authenticated %} {% include "account/snippets/already_logged_in.html" %} {% endif %} <p class="registration-element" style="font-size: 2rem;">{% trans "Trouble Logging In?" %}</p> <p class=" registration-element">{% trans "Enter your email and we'll send you a link to get back into your account." %}</p> <form method="POST" action="{% url 'account_reset_password' %}" class="password_reset"> {% csrf_token %} {% for field in form %} {{ field }} {% endfor %} <input class="signup-button" type="submit" value="{% trans 'Reset My Password' %}"> <p class="" style="text-align: center;">{% blocktrans %}Please contact us if you have any trouble resetting your password.{% endblocktrans %}</p> </form> </div> </div> </div> </div> </div> …