Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create model instance only if its user id field is equal to the logged-in user's id
In a django rest framework app, there's a TextViewSet. The Text object structure is as follows: { text: text_value, author: author_id } When creating a new Text instance, I want to check if the supplied author_id equals the currently logged-in user's id. I've read this question: When to use Serializer's create() and ModelViewset's perform_create(), but still can't decide whether to override Serializer's create(), ModelViewset's create() or perform_create() methods. What's the right method to override? -
How to automatically check if the subscription of the user has expired and to make changes in the model?
I am making a website, where the user chooses a plan that have diferrent durations such as 7days, 14days, 21days. However the plan does not get activated immediately. After the user completes the registation process he has to accept an agreement, and then depending on the type of plan he has choosen the expiration date is set from the date of acceptance, and a field contract_status is set True. Now, I want to know how I can automatically check that the expiration date of a user has reached and set the contract_status of that user to false and then perhaps do some other stuff. But mainly I want to know how I can check subscription expiration automatically to set the field to False. models.py This is the model that has the fields to store the that date of acceptance, expiration and contract status class Contract(models.Model): user = models.OneToOneField(CustomUser, null= True, on_delete=models.CASCADE) contract_status = models.BooleanField(default=False) date_of_acceptance = models.DateTimeField(null= True) date_of_expiration = models.DateTimeField(null=True, blank=True) views.py This is the view that deals with the above model when the user accpets the agreement if request.method == 'POST': agreement = Contract() if request.user.plan == '7days': agreement.user = request.user agreement.contract_status = True expiry = datetime.now() + … -
Static File On Django 3.2 Not Loading
My Problem is quite simple and yet I'm finding it so hard to solve it. The problem is I am not able to load the CSS File and image which are on the static folder located on the root folder of the project. The static folder is not under the app name. My project name is "ecommerce" and my app name is "store". This is my file hierarchy for my project. This is my settings.py I have added my app too. Yes, the STATICFILES_DIRS too. Tried the other one too. STATICFILES_DIRS = [ BASE_DIR / "static", ] I used temp.html for showing the demo and here is my code. And the CSS file which is named main.css After doing all the things properly, the CSS file and image won't load. Errors That I got in my terminal And in developer mode in Chrome As I know this is quite a rookie mistake and I am a beginner. I can't continue forward till this problem is solved. I'd be grateful if someone could come forward and assist me in resolving the issue. -
please explain me what super().save() is exactly doing here (please dont mark it as duplicate question other answers are hard to understand)
please explain me what super().save() is exactly doing here (please dont mark it as duplicate question other answers are hard to understand). Try to keep it easy to understand. I will be very greatfull. Thanks def save(self, *args, **kwargs): original_slug = slugify(self.title) queryset = BlogPost.objects.all().filter(slug__iexact=original_slug).count() count = 1 slug = original_slug while(queryset): slug = original_slug + '-' + str(count) count += 1 queryset = BlogPost.objects.all().filter(slug__iexactf=slug).count() self.slug = slug if self.featured: try: temp = BlogPost.objects.get(featured=True) if self != temp: temp.featured = False temp.save() except BlogPost.DoesNotExist: pass super(BlogPost, self).save(*args, **kwargs) This is the first time i am trying to learn about super().save() and i am finding it difficut to understand from from other answers on stackoverflow -
django-query: get parent value based on children field
I am sorry if I am not very clear with the query I am trying to build, based on the following models: class BankingDetail(models.Model): sfAttachmentID = models.CharField(max_length=18, unique = True) created = models.DateTimeField(auto_now_add=True) class TransactionBankDetail(models.Model): bankingDetail = models.ForeignKey(BankingDetail, on_delete=models.CASCADE, related_name='BankingDetails') institution = models.TextField(blank=True, unique = False, null=True) I am trying to find which institutions I have and how many are they. However, because 1 BankingDetail can have multiple TransactionBankDetail, I want to count this values only once. In other words, based in my query: #institution_by_attachments = TransactionBankDetail.objects.filter(institution__isnull=False).values('bankingDetail__sfAttachmentID', 'institution').annotate(total=1).order_by('total').reverse() institution_by_attachments = TransactionBankDetail.objects.filter(institution__isnull=False).values('bankingDetail__sfAttachmentID', 'institution') for i in institution_by_attachments: print(i) my result will look like {'bankingDetail__sfAttachmentID': '0067F0000bCRuSx', 'institution': 'Atlantic'} {'bankingDetail__sfAttachmentID': '0067F0000bCRuSx', 'institution': 'Atlantic'} {'bankingDetail__sfAttachmentID': '0067F0000bCRuSx', 'institution': 'Atlantic'} {'bankingDetail__sfAttachmentID': '0067F0000bCRuSx', 'institution': 'Atlantic'} {'bankingDetail__sfAttachmentID': 'Ost89Porque-111', 'institution': 'Atlantic'} {'bankingDetail__sfAttachmentID': '0060p000008ieSm', 'institution': 'South Pacific'} {'bankingDetail__sfAttachmentID': '0060p000008ieSm', 'institution': 'South Pacific'} {'bankingDetail__sfAttachmentID': '0060p000008ieSm', 'institution': 'South Pacific'} {'bankingDetail__sfAttachmentID': '0060p000008ieSm', 'institution': 'South Pacific'} {'bankingDetail__sfAttachmentID': '0060p000008ieSm', 'institution': 'South Pacific'} {'bankingDetail__sfAttachmentID': '0060p000008lpYC', 'institution': 'Africa'} {'bankingDetail__sfAttachmentID': '0060p000008lpYC', 'institution': 'Africa'} {'bankingDetail__sfAttachmentID': '0060p000008lpYC', 'institution': 'Africa'} {'bankingDetail__sfAttachmentID': '12365478987test123', 'institution': 'South Pacific'} {'bankingDetail__sfAttachmentID': '12365478987test123', 'institution': 'South Pacific'} {'bankingDetail__sfAttachmentID': '12365478987test123', 'institution': 'South Pacific'} If i use this for my aggregate I will be getting the wrong results: Atlantic 5 South Pacific 8 Africa 3 What I want is: South … -
how to pass the total amount of product to payment gateway
i'm building an ecommerce site with django. once the user press checkout, there is an html billing form which popsup and prompts the user to enter address, email etc. i also passed data like email and it worked fine. but when i try for the amount it doesnt pass how would i pass the amount to the Payment gateway? the Html form <form> <div class="container-fluid"> <div class="row no-gutter"> <div class="col-md-12"> <div class="login d-flex align-items-center py-5"> <div class="container"> <div class="row"> <div id="payment-form" class="col-12 col-lg-6 mx-auto"> <h3 class="mb-3">Billing address</h3> <!-- Error messages in this element --> <div class="row g-3"> <div class="col-sm-7"> <label for="firstName" class="form-label">Full Name</label> <input type="text" class="form-control" id="fullName" placeholder="" required> <div class="invalid-feedback"> Valid first name is required. </div> </div> <div class="col-12"> <label for="email" class="form-label">Email <span class="text-muted">(Optional)</span></label> <input type="email" class="form-control" id="email" placeholder="you@example.com"> <div class="invalid-feedback"> Please enter a valid email address for shipping updates. </div> </div> <div class="col-12"> <label for="address" class="form-label">Address</label> <input type="text" class="form-control" id="custAdd" placeholder="1234 Main St" required> <div class="invalid-feedback"> Please enter your shipping address. </div> </div> <div class="col-12"> <label for="address2" class="form-label">Address 2 <span class="text-muted">(Optional)</span></label> <input type="text" class="form-control" id="custAdd2" placeholder="Apartment or suite"> </div> <div class="col-md-5"> <label for="country" class="form-label">Country</label> <select class="form-select" id="country" required> <option value="">Choose...</option> <option>United States</option> </select> <div class="invalid-feedback"> Please select a … -
Django database access speed depends on host used in request
I am having performance/speed issues in a Python/Django/Postgres application. Specifically, the speed of database queries (via Django's ORM) appears to be related to the hostname used in the request to django. The examples I'm using use either localhost or the VM's hostname (dev.virtual). Using the hostname, performance is good, but using localhost there is a significant slowdown (in the order of tens of times slower). I've created a very basic view to test this: def generate_load_view(request, resource): length = int(request.GET.get("length")) length = 2 ** length iterations = int(request.GET.get("iterations")) iterations = 10 ** iterations if resource == "compute": load_generator = generate_compute_load elif resource == "memory": load_generator = generate_memory_load elif resource == "database": load_generator = generate_database_load else: raise Http404() t_start = time.monotonic() load_generator(length=length, iterations=iterations) t_end = time.monotonic() t_elapsed = t_end - t_start response = {"time": t_elapsed} return Response(response) def generate_database_load(length, iterations): model = django.contrib.contenttypes.models.ContentType pks = model.objects.values_list("pk", flat=True) for _ in range(iterations): random_pk = random.choice(pks) random_obj = model.objects.get(pk=random_pk) I'm using django's ContentType object out of convenience. The database (PostgreSQL) is running in a docker container on the same machine. I've used both django's development server (via manage.py) and a gunicorn server with no appreciable change. To reiterate, if I make a request … -
Ajax URL Not Executing The Correct Function in views.py As Defined in urls.py
I am leveraging Ajax for some pie charts but data-ajax-url is not working as intended (or as I thought). Per urls.py, reptibase:item-update should execute the item_update function in my views.py file. item_update never gets executed though and instead the same function associated with the current pages url is executed again. Currently, am getting a parsing error because HTML is coming back instead of json. json is returned from my item_update function though. item.js window.onload = function () { console.log("Child: ", document.getElementById("piee")) var ctx = document.getElementById("piee").getContext('2d'); var rep_name = $("#pie1").attr("data-rep-name") var ajax_url = $("#pie1").attr('data-ajax-url') var _data = [] var _labels = [] // Using the core $.ajax() method $.ajax({ // The URL for the request url: ajax_url, // The data to send (will be converted to a query string) data: { name: rep_name }, // Whether this is a POST or GET request type: "POST", // The type of data we expect back dataType: "json", headers: {'X-CSRFToken': csrftoken}, context: this }) // Code to run if the request succeeds (is done); // The response is passed to the function .done(function (json) { if (json.success == 'success') { var newMale = json.malePerc var newFemale = json.femalePerc console.log(newMale, newFemale) _labels.push("male", "female") _data.push(parseFloat(newMale), parseFloat(newFemale)) … -
how do I save an image in Django using Cropper.js?
I have a little problem again. I have pictures in my database and it must be possible to crop them at will. I'm trying Cropper.js, but I can't save the image afterwards. What am I doing wrong? I am grateful for all ideas! # index.html {% extends 'base.html' %} {% block content %} <section class="py-5 text-center container"> <div class="row py-lg-5"> <div class="col-lg-6 col-md-8 mx-auto"> <!--<h1 class="fw-light">Album example</h1>--> <form class="bg-light p-4 rounded" method="post"> {% csrf_token %} {{ form }} <button class="btn btn-primary my-2" type="submit"> Получить данные </button> </form> </div> </div> </section> {% for apartment in apartments_list %} <div class="album py-5 bg-light"> <div class="container"> <div class="row row-cols-1 row-cols-sm-6 row-cols-md-2 g-3"> {% for img in apartment.images.all %} <div class="col"> <div class="pop card shadow-sm"> <img src="{{ img.img.url }}" width="100%" height="450" alt="" /> </div> <br /> <div class="d-flex justify-content-between align-items-center"> <div class="btn-group"> <a class="pop btn btn-sm btn-outline-secondary" href="{#% url 'apartments:update-image' img.pk %#}"> Редактировать </a> <a type="button" class="btn btn-sm btn-outline-secondary" href="{% url 'apartments:delete-image' img.pk %}"> Удалить </a> </div> </div> <br /> </div> {% endfor %} </div> <h5 class="card-title">{{ apartment.address }}</h5> <h5 class="card-title">{{ apartment.rooms }}</h5> <h5 class="card-title">{{ apartment.floor }}</h5> <h5 class="card-title">{{ apartment.price }}</h5> <p class="card-text">{{ apartment.desc }}</p> <div class="btn-group"> <a type="button" class="btn btn-sm btn-outline-secondary" href="{% url 'apartments:update' … -
The block in my template gets rendered with an incorrect indentation
I have this problem where my block are correctly indented in the template, but when it gets rendered the indentation fails and all the text of my post get out of place. To clarify I'm using django to create a blog. It's just a personal project, I just stated learning like 4 months ago. Actual Blog This is the source code I get: Source Code As you can see all the code should be to the right side of the red line. I don't know what is happening. I have been trying everything for the last 4 hours and nothing. The thing is, this is my firth project so I made a lot of mistakes. When this problem appeared for the first time I didn't pay much attention to it, I thought it was just a html code problem and easy to solve. Now I'm lost. This is a part of the code of my Base template, where the block is: <!-- Main Content--> <div class="container px-4 px-lg-5"> <div class="row gx-4 gx-lg-5 justify-content-center"> <div class="col-md-10 col-lg-8 col-xl-7"> <!-- Post preview--> <div class="post-preview"> {% block content %} {% endblock %} </div> </div> </div> </div> This is the code of my home: … -
How can I add an extra field in the response to understand which item triggered the search result
I have a simple recipe and ingredient models. class Ingredient(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False) name = models.CharField(db_column='name', max_length=200, blank=False, null=False, unique=True) class Recipe(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False) name = models.CharField(db_column='name', max_length=200, blank=False, null=False, unique=True) ingredients = models.ManyToManyField(Ingredient, related_name='product_ingredients') I have added a filter for recipe search when I can add ingredient ids as parameter. It returns the recipes which have those ingredients. The filter is as follows, class RecipeFilter(django_filters.FilterSet): ingredient_have = django_filters.CharFilter(method='filter_ingredient_have') def filter_ingredient_have(self, queryset, name, value): if value: ids = value.split(',') return queryset.filter(Q(ingredients__id__in=ids)) return queryset class Meta: model = Recipe fields = [] The url is something like this /recipes/?ingredient_have=id1,id2 The response is something like { "items": [ { "id": "13261f0d-408d-4a51-9cc2-cb69ee72fe24", "name": "Curry", "ingredients": [ { "id": "08089ff8-03fb-4946-be61-659d799ca996", "name": "oil" }, { "id": "dc9cb6f2-1810-48eb-b7a7-52a4bd9fdccb", "name": "water" } ] } ] } I would like to add an extra field (in Ingredient) so that I can understand in the frontend which ingredient has triggered the product to be in the search result such as, { "id": "08089ff8-03fb-4946-be61-659d799ca996", "name": "oil", "highlight": false/true } I hope I made the problem clear. Could you please give me some suggestion/solution? Thanks in advance. -
If the value recieved in a Decimal Form is an empty string how can I convert it to a float number?
On my page I ask for various things to the user in the form as it's a calculator that does various things, now you see, the thing is if the user does not have the value for bf I want to give the option to calculate with different values, that is why I required is False, so first what I want to archive is that if the form is empty I want to be passed as a 0 or False, how can I archive this? I have the following form: class CMForm(forms.Form): age = forms.DecimalField(max_digits=2, decimal_places=0, min_value=15, max_value=80) sex = forms.ChoiceField(choices=sex) pregnant = forms.BooleanField(initial=False, required=False) lactating = forms.BooleanField(initial=False, required=False) weight = forms.DecimalField(max_digits=4, decimal_places=1, max_value=635) height = forms.DecimalField(max_digits=4, decimal_places=1, max_value=272) bf = forms.DecimalField(label='Body Fat(not required)', help_text='%', required=False, decimal_places=1, min_value=1, max_value=80) activeness = forms.ChoiceField(choices=activity_level) units = forms.ChoiceField(choices=units) this view: def cmr(request): a = float(request.GET['age']) bf = float(request.GET.get('bf', 0)) s = str(request.GET['sex']) g = 0 if s == 'female': g = 1 w = float(request.GET['weight']) h = float(request.GET['height']) act = str(request.GET['activeness']) u = str(request.GET['units']) p = str(request.GET.get('pregnant', 0)) lac = str(request.GET.get('lactating', 0)) dci = 0 bmrm = 10*w+6.25*h-5*a+5 bmrf = 10*w+6.25*h-5*a-161 bmi = round(w/(h/100)**2, 1) if bf is False: bf = round(-44.988 + … -
Error when requesting User.history.all ()
I have a model class User (AbstractUser), I would like to keep track of the User history, I have an error while getting User.history.all (), ERROR: table "core_user" is missing from the FROM clause LINE 1: SELECT "core_user". "Id", "core_user". "Password", "core_user" ... SELECT "core_user"."id", "core_user"."password", "core_user"."last_login", ' '"core_user"."is_superuser", "core_user"."username", ' '"core_user"."first_name", "core_user"."last_name", "core_user"."email", ' '"core_user"."is_staff", "core_user"."is_active", "core_user"."date_joined", ' '"core_user"."editor_config", "dib_page_historicaluser"."ip_address", ' '"dib_page_historicaluser"."history_id", ' '"dib_page_historicaluser"."history_date", ' '"dib_page_historicaluser"."history_change_reason", ' '"dib_page_historicaluser"."history_type", ' '"dib_page_historicaluser"."history_user_id" FROM "dib_page_historicaluser" ' 'ORDER BY "dib_page_historicaluser"."history_date" DESC, ' '"dib_page_historicaluser"."history_id" DESC LIMIT 21') core_user table it is my base_model, dib_page_historicaluser table it is history model, whoever knows can tell what the problem is, I'm a beginner -
Tried to create three apps in Django but when try to click on third app it routes to the second app page settings templates DIR allows routing 2 DIRs
in this below code i explained How i rooted the templated but only first two roots are working when click on my third app it automatically rooted to my second app #--assigning apps templates as values-- mail = os.path.join(BASE_DIR,'mail/templates') cloud = os.path.join(BASE_DIR,'cloud_storage/templates') TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', #--rooting the values as dirs -- 'DIRS': [BASE_DIR/'Home/templates',cloud,mail,], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
SQL0601N The name of the object to be created is identical to the existing name "DJANGO_MIGRATIONS" of type "TABLE"
I want the django to connect to db2 as another user (a DBADM) instead of db2inst1, the schema is XXX. but after running python manage.py migrate, it failed after creating tables DJANGO_MIGRATIONS and DJANGO_CONTENT_TYPE. They are both empty. The returned error is [IBM][CLI Driver][DB2/AIX64] SQL0601N The name of the object to be created is identical to the existing name "XXX.DJANGO_MIGRATIONS" of type "TABLE". SQLSTATE=42710. I tried to drop tables and run the command again but failed. It seems it cannot find the DJANGO_MIGRATIONS table when trying to insert a new record so it tries to create it again. The command however succeeds when using db2inst1. So I want to know if the issue is caused by insufficient user privileges? What privileges/roles the connection user should have? Are there any restrictions on the connection user? I tried to find document but couldn't find any. Versions: Django 3.2, ibm-db-django 1.5.0.0, ibm-db 3.1.0, DB2 10.5 -
Container command fails when deploying
I'm trying to deploy my Django project using Elastic Beanstalk. It's been fine until it tried to run container commands. Here's my .config file looks like: container_commands: 01_migrate: command: "source /var/app/venv/*/bin/activate && python3 manage.py migrate" leader_only: true 02_createsuperuser: # <- The error occurs here command: "echo \"from account.models import Account; Account.objects.create_superuser('Me', 'Me', 'myemail@gmail.com', 'superadmin', 'MyPassword')\" | python3 manage.py shell" And my cfn.init file logs this error: [ERROR] Command 02_createsuperuser (echo "from account.models import Account; Account.objects.create_superuser('Me', 'Me', 'myemail@gmail.com', 'superadmin', 'MyPassword')" | python3 manage.py shell) failed 2021-12-06 03:22:18,662 [ERROR] Error encountered during build of postbuild_0_package404: Command 02_createsuperuser failed Traceback (most recent call last): File "/usr/lib/python3.7/site-packages/cfnbootstrap/construction.py", line 573, in run_config CloudFormationCarpenter(config, self._auth_config).build(worklog) File "/usr/lib/python3.7/site-packages/cfnbootstrap/construction.py", line 273, in build self._config.commands) File "/usr/lib/python3.7/site-packages/cfnbootstrap/command_tool.py", line 127, in apply raise ToolError(u"Command %s failed" % name) cfnbootstrap.construction_errors.ToolError: Command 02_createsuperuser failed 2021-12-06 03:22:18,665 [ERROR] -----------------------BUILD FAILED!------------------------ 2021-12-06 03:22:18,665 [ERROR] Unhandled exception during build: Command 02_createsuperuser failed Traceback (most recent call last): File "/opt/aws/bin/cfn-init", line 176, in <module> worklog.build(metadata, configSets) File "/usr/lib/python3.7/site-packages/cfnbootstrap/construction.py", line 135, in build Contractor(metadata).build(configSets, self) File "/usr/lib/python3.7/site-packages/cfnbootstrap/construction.py", line 561, in build self.run_config(config, worklog) File "/usr/lib/python3.7/site-packages/cfnbootstrap/construction.py", line 573, in run_config CloudFormationCarpenter(config, self._auth_config).build(worklog) File "/usr/lib/python3.7/site-packages/cfnbootstrap/construction.py", line 273, in build self._config.commands) File "/usr/lib/python3.7/site-packages/cfnbootstrap/command_tool.py", line 127, in apply raise ToolError(u"Command %s … -
Insertion with 1 foreign key and 2 pk failed
class TbBoard(models.Model): board_seq = models.BigAutoField(primary_key=True) board_title = models.CharField(max_length=30) board_content = models.CharField(max_length=2000, blank=True, null=True) board_writer = models.CharField(max_length=40) board_password = models.CharField(max_length=200) create_date = models.DateTimeField(default=timezone.now) class Meta: managed = False db_table = 'tb_board' class TbComment(models.Model): board_seq = models.ForeignKey(TbBoard, models.DO_NOTHING, db_column='board_seq') comment_seq = models.IntegerField(primary_key=True) comment_depth = models.IntegerField() comment_content = models.CharField(max_length=2000) comment_writer = models.CharField(max_length=40) comment_password = models.CharField(max_length=200) create_date = models.DateTimeField(default=timezone.now) class Meta: managed = False db_table = 'tb_comment' unique_together = ('board_seq', 'comment_seq', 'comment_depth',) The part to save is as follows. tb_comment = models.TbComment( board_seq = models.TbComment.objects.get(board_seq=board_seq), comment_seq = comment_seq, comment_depth = comment_depth, comment_content = comment_content, comment_writer = comment_writer, comment_password = comment_password, ) board_seq=1, comment_seq=0, comment_depth=0 In the state that is inserted in this db board_seq=2, comment_seq=0, comment_depth=0 I'm trying to insert board_seq=1 -> 2, comment_seq=0, comment_depth=0 will be overwritten by how can i solve it?? force_insert=true? When you try, the already existing key(0, 0) is output like this. -
Django: 'WSGIRequest' object has no attribute error
I've two models in my app: the Dataset model is created when the File model is saved, but I'm having problem linking the file_uploaded field in the dataset to the File model using foreign key. To do so I'm using this: file_uploaded = request.file_uploaded.file, and I'm getting this error: 'WSGIRequest' object has no attribute 'file_uploaded' I'm not getting what I'm doing wrong considering that I can link the user without problems. I had to change a little bit of my code to make it shorter, there may be some inconsistenciesbut, but the original one works (excepts for the error I'm getting). Thank you all for the help MODEL class File(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) filename = models.CharField(max_length=250) file_upload = models.FileField(upload_to=path) upload_date = models.DateField(default=datetime.now) def __str__(self): return self.user.name + 'file' class Dataset(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) file_uploaded = models.OneToOneField(File, on_delete=models.CASCADE) name_user_A = models.CharField(max_length=250) code_user_A = models.PositiveIntegerField(null=True) total_user_A = models.PositiveIntegerField(null=True) sd_user_A = models.PositiveIntegerField(null=True) name_user_B = models.CharField(max_length=250) code_user_B = models.PositiveIntegerField(null=True) total_user_B = models.PositiveIntegerField(null=True) sd_user_B = models.PositiveIntegerField(null=True) With File model it should be uploaded a csv file and then the information in the file should be saved in the Dataset model. After that I'd like to show some chart to my user so I … -
Custom inputs of django-filter in templeta
I want to improve the rendering of the inputs in the template. I have tried adding styles from widgets in the class: class ProductosFilter(django_filters.FilterSet): class Meta: model = Elemento fields = ('estado','tipo','grupo') widgets = { 'grupo':widgets.Select(attrs={ 'class': 'form-control form-select ', }), } but I did not make it. this is my template: <div class="col-md-12" style="text-align: right; padding-top: 50px; padding-right: 50px;" > {{filter.form}} <button type="submit" class="btn btn-primary">Filtrar</button> </div> any contribution is appreciated -
If the value recieved in a Decimal Form is an empty string how can I convert it to a float number?
On my page I ask for various things to the user in the form as it's a calculator that does various things, now you see, the thing is if the user does not have the value for bf I want to give the option to calculate with different values, that is why I required is False, so first what I want to archive is that if the form is empty I want to be passed as a 0 or False, how can I archive this? I have the following form: class CMForm(forms.Form): bf = forms.DecimalField(label='Body Fat(not required)', help_text='%', required=False, decimal_places=1, min_value=1, max_value=80) this view: def cmr(request): a = float(request.GET['age']) bf = float(request.GET.get('bf')) s = str(request.GET['sex']) g = 0 if s == 'female': g = 1 w = float(request.GET['weight']) h = float(request.GET['height']) act = str(request.GET['activeness']) bf = float(request.GET.get('bf')) bmi = round(w/(h/100)**2, 1) if bf is False: bf = round(-44.988 + (0.503 * a) + (10.689 * g) + (3.172 * bmi) - (0.026 * bmi**2) + (0.181 * bmi * g) - (0.02 * bmi * a) - (0.005 * bmi**2 * g) + (0.00021 * bmi**2 * a), 1) tbf = w*(bf/100) ffm = w*(1-(bf/100)) ffmi = ffm/(h/100)**2 nffmi = … -
Cannot unpack non-iterable object Django
So, I'm trying to filter a field's choices by the created_by attribute, which is an User instance gotten from the request when it was created. After doing some research I found some explanations and followed them but I couldn't get the choices to actually appear at the form. Now I'm getting the error that Categoria Object isn't Iterable. The error Django shows me at the browser: Exception Type: TypeError Exception Value: cannot unpack non-iterable Categoria object the Class I used as a model to the Form: class Contato(models.Model): nome = models.CharField(max_length=255) sobrenome = models.CharField(max_length=255, blank=True) telefone = models.CharField(max_length=255) email = models.CharField(max_length=255, blank=True) data_criacao = models.DateTimeField( default=timezone.now) descricao = models.TextField(blank=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE) categoria = models.ForeignKey( Categoria, on_delete=models.DO_NOTHING) mostrar = models.BooleanField(default=True) foto = models.ImageField(blank=True, upload_to='fotos/%y/%m/%d') def __str__(self): return self.nome this is the code from the Form I'm trying to modify class ContatoForm(forms.ModelForm): class Meta: model = Contato exclude = ('created_by',) def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(ContatoForm, self).__init__(*args, **kwargs) category_choices = list(Categoria.objects.filter( created_by=self.user)) self.fields['categoria'] = forms.ChoiceField(choices=category_choices) And this is the view I'm using this form at @login_required(redirect_field_name='login') def dashboard(request): if request.method != 'POST': form_contato = ContatoForm(user=request.user) form_categoria = CategoriaForm return render(request, 'accounts/dashboard.html', {'form_contato': form_contato, 'form_categoria': form_categoria}) -
Need help in django
I have 4 model classes (Course, Semester, Subject, TuModelQuestions) as you can see below. When I try to render particular question from TuModelQuestions from Partcular Subject From Particular Semester And particuar Course. How do i render it? Please give me some logic and code if you can. (Overall: I want to render that question only for particular subject, course and semester) models.py from django.db import models from django.db.models.base import ModelState # Create your models here. class Course(models.Model): faculty = models.CharField(max_length=100) class Semester(models.Model): sem = models.CharField(max_length=100) faculty = models.ForeignKey(Course, on_delete=models.CASCADE) def __str__(self): return F"Semester {self.sem} at Faculty {self.faculty}" class Subject(models.Model): faculty = models.ForeignKey(Course, on_delete=models.CASCADE) sem = models.ForeignKey(Semester, on_delete=models.CASCADE) subject_name = models.CharField(max_length=100) class TuModelQuestions(models.Model): date = models.IntegerField() model_question = models.ImageField(upload_to='imgs/') subject = models.ForeignKey(Subject, on_delete=models.CASCADE) views.py from django.shortcuts import render from django.views import View from django.contrib import messages from django.contrib.auth.forms import UserCreationForm, AuthenticationForm, UsernameField from django import forms from django.utils.translation import gettext, gettext_lazy as _ from .forms import CustomerRegistrationForm from .models import Course, Semester, Subject, TuModelQuestions # Create your views here. def home(request): return render(request, 'app/home.html') def faculty(request): course = Course.objects.all() return render(request, 'app/faculty.html', {'course':course}) class SemesterView(View): def get(self, request,id): obj = Course.objects.get(id=id) print(obj) semobj = Semester.objects.filter(faculty=obj) print(semobj) subobj = Subject.objects.filter(faculty=obj) print(subobj) return … -
Django - "psycopg2.errors.ForeignKeyViolation: insert or update on table" when running "python manage.py test", but not when running single test
So I made another post regarding this issue and thought I'd break it down even more to see if the good people of StackOverflow can figure out what's going on, because I can't. So I generate all this test data below using setUpTestData and things look good. I put the debugger log below to show that the test database is populated with what is expected. When I get to the test test_correct_num_posts_generated the test itself passes, but I get this weird database error. I put the full error output below. I've gotten this over many tests. I heard it could be related to a Django bug where the test DB doesn't get properly torn down. This is a weird issue, because when I run python manage.py test cheers.test.ExploreTest it passes and python manage.py test cheers.test.ExploreTest.test_correct_num_posts_generated it passes, but when I run python manage.py test I get the error shown below. What is going on? Test.py @classmethod def setUpTestData(cls) -> None: cls.num_posts = 45 cls.health_cate = 'Health' cls.fitness_cate = 'Fitness' cls.relationship_cate = 'Relationship' cls.goal_categories_name_list = [cls.health_cate, cls.fitness_cate, cls.relationship_cate] cls.user = create_test_user_in_DB() cls.access_token = get_test_user_access_token() for name in cls.goal_categories_name_list: goal_category_obj = GoalCategory.objects.create(name=name, emoji='Some URL') goal_obj = Goal.objects.create(creator=cls.user, goal_category=goal_category_obj) if name == cls.relationship_cate: … -
Sending email from DebuggingServer localhost:1025 not working
Im testing sending an email after filling out a form on a website and im using my local host. Upon submitting the form I'm using the django send_mail() method and Im sending the test email to a gmail account and I have the account as a list data type. $ python -m smtpd -n -c DebuggingServer localhost:1025 And I'm getting this depreciated message after I turn on the server and I also have yet to receive an email from my local host C:\Users...\AppData\Local\Programs\Python\Python310\lib\smtpd.py:104: DeprecationWarning: The asyncore module is deprecated. The recommended replacement is asyncio import asyncore C:\Users...\AppData\Local\Programs\Python\Python310\lib\smtpd.py:105: DeprecationWarning: The asynchat module is deprecated. The recommended replacement is asyncio import asynchat Here's whats in my settings.py file: EMAIL_HOST = 'localhost' EMAIL_PORT = 1025 EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' EMAIL_USE_TLS = False Any ideas why its not sending? -
Django ModuleNotFoundError: No module named "\n 'hello"
I am following Django dj4e course. While going through setup that is linked here https://www.dj4e.com/assn/dj4e_ads1.md?PHPSESSID=991c1f9d88a073cca89c1eeda44f61d2 I got this weird error: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/cisco18/.virtualenvs/django3/lib/python3.6/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/cisco18/.virtualenvs/django3/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/home/cisco18/.virtualenvs/django3/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/cisco18/.virtualenvs/django3/lib/python3.6/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/cisco18/.virtualenvs/django3/lib/python3.6/site-packages/django/apps/config.py", line 212, in create mod = import_module(mod_path) File "/usr/local/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import ... bunch of similar bootstrap lines ... ModuleNotFoundError: No module named "\n 'hello" I got this error when I did everything in the tutorial's setup and then copied the settings because they were missing something. I went through all those steps again and this weird error keeps popping up during python3 manage.py check. Here are my 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__))) # Used for a default title APP_NAME = 'ChucksList' # Add # 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! …