Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Initial value of django form field with django tag value
I have created a django form. This form is used to update the values of an existing object. That's why I want to show initial values which are taken from django variables inside django tags. Here is the django form. class RevisionStatusForm(forms.ModelForm): """ Update Revision""" class Meta: model = Revision widgets = { 'status': forms.Select(attrs={'required': True}),} fields = ['status','remark'] on my HTML template, here is how it currently looks: <td>{{revisionstatusform.remark}}</td> Here is how I want it to work: <input type="text" name="remark" value="{{revision.remark}}">. I want to show revision.remark variable value inside input field created from django forms. I don't know how to do it. Can anyone help? -
How to get the authentificated user information in Model Serializer in Django Rest?
I have a LinkList object, which has owner property - the username of the User it belongs to. I am trying to have LinkLists be linked to the user that made the create request, however self.context['request'].user and CurrentUserDefault don't work in my create method, so I cannot create an instance of the LinkList object. The error I am getting: NOT NULL constraint failed: llists_linklist.owner_id Here is the serializer: class LinkListSerializer(serializers.ModelSerializer): url = serializers.HyperlinkedIdentityField(view_name="lists-detail") owner = serializers.ReadOnlyField(source='owner.username') links = LinkSerializer(many=True) class Meta: model = LinkList fields = ['url', 'owner', 'name', 'public', 'links'] def create(self, validated_data): links = validated_data.pop('links', []) instance = super().create(validated_data) for item in links: instance.links.add(link=item) return instance The model: class LinkList(models.Model): owner = models.ForeignKey( User, related_name='lists', on_delete=models.CASCADE) name = models.CharField(max_length=100) description = models.CharField(max_length=250) public = models.BooleanField(default=False) links = models.ManyToManyField( Link, related_name='linklists') def __str__(self): return "%s - %s" % (self.owner, self.name) def save(self, *args, **kwargs): super().save(*args, **kwargs) -
html iterate through dictionary in django and button download
i am working on an app on django 2 pbl: i used defaultlist but not working nothing on my output , my button download is not working : i received this error :"AttributeError at /views.download_my_pdf 'str' object has no attribute 'read' " I want to download my home page to pdf what i did wrong please? Django views.py from django.shortcuts import render from django.core.files.storage import FileSystemStorage import pandas as pd import datetime from datetime import datetime as td import os from collections import defaultdict from django.http import HttpResponse from wsgiref.util import FileWrapper def home(request): if request.method == 'POST': uploaded_file = request.FILES['document'] uploaded_file2 = request.FILES['document2'] if uploaded_file.name.endswith('.xls'): savefile = FileSystemStorage() name = savefile.save(uploaded_file.name, uploaded_file) name2 = savefile.save(uploaded_file2.name, uploaded_file2) d = os.getcwd() file_directory = d+'\\media\\'+name file_directory2 = d+'\\media\\'+name2 results,output_df =results1(file_directory,file_directory2) return render(request,"results.html", {"results":results,"output_df":output_df,}) return render(request, "index.html") def readfile(uploaded_file): data = pd.read_excel(uploaded_file, index_col=None) return data def results1(file1,file2): results_list = defaultdict(list) names_loc = file2 listing_file = pd.read_excel(file1, index_col=None) for x in date_index: if time>2h: results_list["List of samples better"].append(sample_id) if len(u_index) > 1: results_list["List of Samples "].append(sample_id) output_df = output_df.append(row_to_add, ignore_index=True) else: results_list["List of Samples not in the listing file"].append(sample_name[0]) except: print('The template name isnt good: {}'.format(sample_id)) return results_list, output_df.to_html() def download_pdf(request): filename = 'faults.pdf' … -
I want to check filtered field at drop-down in django-admin
When the classification field is checked, I want to filter only the values according to the classification filed so that it can be checked in the dropdown. and I installed django-clever-selects. i usually the choicefields were written in the models.py, but django-clever-selects seemed to be usually put in and used at helpers.py, so I did. when i checked in the account_classification field at models.py in admin (tuple content of helpers.py 'expenses'), i want to check only the filtered field in the account_category field (tuple content of helpers.py CATEGORY). In the form of the picture below. enter image description here # models.py class AccountBook(TimeStampedModel): branch = models.ForeignKey(Branch, on_delete=models.CASCADE, null=False) account_amount = models.PositiveIntegerField(validators=[MinValueValidator(0)], null=False, verbose_name="금액") # 금액 account_reference = models.CharField(max_length=200, null=True, verbose_name="참조내용") account_manager = models.CharField(max_length=10, null=False, verbose_name="담당자") account_recoder = models.CharField(max_length=10, null=False, verbose_name="기록자") # account_classification = models.CharField(choices=EXPENSES, max_length=100, null=True, blank=True, verbose_name="분류") # 분류 - 저장시킬 필드 # account_category = models.CharField(choices=CATEGORY, max_length=100, null=True, verbose_name="범주") # 범주 - 저장시킬 필드 # forms.py class AccountBookForm(ChainedChoicesForm, forms.ModelForm): account_classification = ChoiceField(choices=[('', (u'Select a classification'))] + list(EXPENSES)) account_category = ChainedChoiceField(parent_field='account_classification', ajax_url=reverse_lazy('ajax_chained_category'), empty_label=(u'Select category')) class Meta: model = AccountBook fields = ["branch", "account_classification", "account_category", "account_amount", "account_reference", "account_manager", "account_recoder"] views.py class SimpleChainView(FormView): form_class = AccountBookForm template_name = '/' success_url = '/' … -
Can we merge multiple pdf in django with weasyprint?
https://weasyprint.org/ I have two different pdfs and want to merge than using weasyprint so that whenever the user downloads the pdf it should download the pdf which consists of the both the pdf in single one -
The connection to postgresql on django is not working and some issues were found after migrating
`DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'todoDB', 'USERNAME': 'postgres', 'PASSWORD': 'admin', 'HOST': 'localhost', } }` command prompt error Traceback (most recent call last): django.db.utils.OperationalError: connection to server at "localhost" (::1), port 5432 failed: FATAL: password authentication failed for user "admin" -
How to get highest bid for every item in an auction bidding site Django
So I have a Django auctions app, which has 3 models: Users, Listings, Bids. When a user tries to place a bid on some listing, I want to check if the new_bid field in Bid model is bigger than start current_bid field in Listing model and if the new_bid is <= 0, it should return a message. This is what I've done so far but when I click on 'Place bid' button, it does not implement this (it does not show any message for any of the above scenario and my count does not increase) meaning that the form is not submitting. Why is this not working? VIEWS.PY def listing_detail(request, listing_id): try: detail = get_object_or_404(Auction, pk=listing_id) except Auction.DoesNotExist: messages.add_message(request, messages.ERROR, "This is not available") return HttpResponseRedirect(reverse("index")) bid_count = Bids.objects.filter(auction=listing_id).count() context = {'detail': detail, 'bid_count': bid_count, 'bidForm': BidForm()} return render(request, 'auctions/details.html', context) @login_required def make_bid(request, listing_id): if request.method == 'POST': form = BidForm(request.POST) if form.is_valid: each_listing = Auction.objects.get(pk=listing_id) highest_bid = Bids.objects.filter(pk=listing_id).order_by('-new_bid').first() new_bid = form.cleaned_data.get['new_bid'] if new_bid <= 0: return render(request, 'auctions/details.html', {"message": "Input an amount greater than 0"}) # messages.add_message(request, messages.SUCCESS, "Input an amount greater than 0") elif new_bid <= highest_bid.new_bid: messages.add_message(request, messages.ERROR, "Amount is low, please increase the bid") else: … -
Attribute Error when Running Django Rest API
I have created a simple project called djangowallet and inside that project, I have created an app called wallet with a model wallet and just one field called raddress. I have created the serializer, views and URLs and when I runserver it gives the following error. PS C:\Users\Ahmed\djangowallet> python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Ahmed\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Users\Ahmed\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "C:\Users\Ahmed\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Ahmed\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "C:\Users\Ahmed\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 438, in check all_issues = checks.run_checks( File "C:\Users\Ahmed\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\checks\registry.py", line 77, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Ahmed\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\Ahmed\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Ahmed\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\resolvers.py", line 448, in check for pattern in self.url_patterns: File "C:\Users\Ahmed\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Ahmed\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\resolvers.py", line 634, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Ahmed\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Ahmed\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\resolvers.py", line 627, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Ahmed\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, … -
How can we send bulk_email in django using different from_emails?
I have 1 Django app and i want to send bulk_email to multiple users, so normally it will send from only 1 from_email. Now how can I send bulk_email from different from_email when I select 1 email from the dropdown list? -
How to mock instance attribute of django form
I'm doing a unit test where I'm mocking a Django form, but I'm having some trouble because I need to mock two things from the form: An instance attribute (token) A method (is_valid) I'm using the form in a view, importing it like this: from profiles.forms import PaymentForm And I have tried the following to mock it: @patch('profiles.forms.PaymentForm') def test_when_processing_a_payment_then_the_event_is_tracked(self, payment_form_class): payment_form_class.is_valid.return_value = True payment_form_class.cleaned_data = {'token': 1} This approach does not work, is_valid returns false. @patch('profiles.forms.PaymentForm') def test_when_processing_a_payment_then_the_event_is_tracked(self, payment_form_class): payment_form_class.return_value.is_valid = True payment_form_class.return_value.cleaned_data = {'token': 1} This neither. I'm using Django and unittest. I have successfully mocked the is_valid with a helper function of our code base, but it does not seem to work with instance attributes. Any idea how to solve this? -
Calculate age from date of birth using django orm query
I am calculating age using python code like age = datetime.date.today().year - patient_table.dob.year - ((datetime.date.today().month, datetime.date.today().day) < (patient_table.dob.month, patient_table.dob.day)) i return correct age. but i need this result using Django orm query how i can do this? i tried like, PatientTable.objects.filter(is_active=True,is_deleted=False).annotate(age=datetime.date.today().year - F('dob__year')) but it getting wrong age. -
How can I loop salary amount against each employees?
I want my python to print the name of employees one by one (in a loop) and let me add the salary amount against each employee and in the last create a dictionary (key-value) for me, the key is employee name and value is amount and I also want to print out the total amount of salary means the sum of all the salaries. How can I do that That is what I did so far: employees = ["abc", "def", "ghi", "jkl", "mno", "pqr"] n=0 amonut= 0 try: for employee in employees: employee = employees[n] amount= int(input(amount)) total = sum(amount) n=n+1 print(total) except: print("You can only type integer for amount") I have no idea how to create a dictionary in the last -
Django filter search with dropdown
In Django, while taking entry from the user, I have created a dropdown from which user can select the field, but that dropdown can be longer. What I want is, it should also contain a filter search box where the user will enter the keyword and the fields related to that keyword will appear in front. Here is the screenshot of the current UI:- This is the code for selecting the "Annual Work Plan":- <div id="div_Select_Annual_Work_Plan" class="form-group col-md-4"> {{ form.Select_Annual_Work_Plan.label_tag }} {{ form.Select_Annual_Work_Plan }} {{ form.Select_Annual_Work_Plan.errors }} {% if form.Select_Annual_Work_Plan.help_text %} <p class="help">{{ form.Select_Annual_Work_Plan.help_text }}</p> {% endif %} </div> Inside forms.py, the field for "select annual work plan" is described as follows:- Select_Annual_Work_Plan = forms.ModelChoiceField(queryset=annual_work_plan.objects.none().order_by("Annual_Work_Plan_ID"), label='Select Annual Work Plan', ) Please let me know, in case any other piece of code is needed. I am new to Django and didn't find any solution on the internet. -
I cannot search a field when i added a serializermethod in documentviewset
class VariantSerializers(DocumentSerializer): uom = serializers.SerializerMethodField('get_uom') def get_uom(request,obj): if obj.uom_id is not None: uomData = Uom.objects.filter(code=obj.uom_id).first() if uomData is None: return obj.uom_id return uomData.name class Meta: model = Variant document = VariantDoc fields = '__all__' Here i added a serializermethod and here i cannot search with uom name but it's not working -
how to redirect from a function to a url using name attribute + "?next=next_path" in django redirect?
view.py def register(request): next_cart_page = request.GET.get('next', '') if request.method == 'POST': status = logic.register_logic(request) if next_cart_page == 'cart': return redirect("/u/o/?next="+ next_cart_page) <- instead of "/u/o/" how can i use "verify_otp_user" else: return redirect("verify_otp_user") main.js $('.checkout_login_required').click(function(){ $('#register_user_link').attr('href', function(i, val){ return val + '?next=cart' }) }); using javascript i'm passing a value to the next key to an anchor tag. then on views.py i'm checking for that value in an if statement and based on that i'm redirecting to the next page with or without the next value in else statement i'm using path name attribute to redirect to a url how can i do the same in if statement as well while concatinating path name attribute(like verify_otp_user) with "?next=" + next_cart_page something like redirect("verify_otp_user" + "?next=" + next_cart_page), but this is not working . Any alternate solution if available ? Note: verify_otp_user does not have any parameter in its url its simply /u/o/ -
how to save multiple products in a single run
i have this issue trying to save de Order(detalle products) from my Sale, i don't know how to do it class Sale(models.Model): sale_id = models.IntegerField(primary_key=True) cli = models.ForeignKey(Clientes ,on_delete=models.CASCADE,null=True) date_joined = models.DateField(default=datetime.now) subtotal = models.DecimalField(default=0.00, max_digits=9, decimal_places=2) iva = models.DecimalField(default=0.00, max_digits=9, decimal_places=2) total = models.DecimalField(default=0.00, max_digits=9, decimal_places=2) class Order (models.Model): order_id = models.AutoField(primary_key=True) orden = models.IntegerField() sale_id = models.ForeignKey(Sale ,on_delete=models.CASCADE,null=True) codigo_producto = models.IntegerField() precio = models.IntegerField() cantidad = models.IntegerField() above you can see my to models and here is how i called in my views def mod_venta(request,orden_actual=0): if request.session.get("codigo_usuario"): listaorder=Order.objects.all() listatabla=producto.objects.all() listacliente=Clientes.objects.all() if request.method=="GET": return validar(request, "venta.html",{"listaorder":listaorder,"listacliente":listacliente,"listatabla":listatabla}) if request.method=="POST": if orden_actual==0: venta_nueva=Order(order_id=request.POST.get('orden_actual'), codigo_producto=request.POST.get('codigo'), precio=request.POST.get('precio'), cantidad=request.POST.get('canti')) venta_nueva.save() return redirect("../venta/0") else: return redirect("login") and only try to save with a form, only saving one element in the "OrderDetalle", (i only work with for a month ) so I wanted to know how I could do to bring all the sales data in orders -
Error get static file from another project
I'm on Network project but when I runserver this project, it get static file from my another project is Mail, static file in Network project still work ok, but it appear error in my Terminal and I don't know how to solve it ! Network |-static |-network |-style.css |-index.js [21/Feb/2022 12:22:48] ←[33m"GET /static/mail/inbox.js HTTP/1.1" 404 1667←[0m setting.py STATIC_URL = '/static/' -
Import the csv data to database and update the existing data using their id in django
I want to update some existing data by uploading the CSV file. I have some data in the MySQL database and some of them have spelling mistakes and some others mistakes. So I have correct data on the CSV file and I want to upload it and update existing data on the database. Below code for importing data into the database. So how can I modify this code to update the existing data of the database? views.py # Import the data to database def import_countries(request): with open('C:/python/Azuro/azuro_django/pms/templates/pms/countryname.csv') as csvfile: reader = csv.DictReader(csvfile) for row in reader: data = Country(currency=row['Currency'], name=row['Country']) data.save() return HttpResponse('Data Uploaded!!') Thanks! -
Django rest framework API key is not able to authenticate when using custom models
I am using rest_framework_api_key for authenticating services those use our API, I have following versions of Django, Rest framework and rest_framework_api_key Django==3.2.12 djangorestframework==3.13.1 djangorestframework-api-key==2.1.0 My Installed Apps in settings.py INSTALLED_APPS = [ 'django_extensions', 'django_elasticsearch_dsl', 'drf_yasg', 'media_fetchers', 'api_registration', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework_api_key', 'corsheaders', 'admin_panel', 'accounts', ] Default Permissions classes REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework_api_key.permissions.HasAPIKey', 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], "TEST_REQUEST_DEFAULT_FORMAT": "json", "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.LimitOffsetPagination", "PAGE_SIZE": 20, } My Models for using APIKey model class Service(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="service") name = models.CharField(max_length=128) active = models.BooleanField(default=True) class ServiceAPIKey(AbstractAPIKey): organization = models.ForeignKey( Service, on_delete=models.CASCADE, related_name="api_keys", ) So I have created an API in which permission_classes = [HasAPIKey] which is not authenticating and it gives the response authentication credentials were not provided. I passed the API key in postman in headers just like it was mentioned in the official docs Django rest API key The twist is when I remove the models and use their APIKey model as it is, it does authenticate with HasAPIKey... Anything I am doing wrong? I also read all the issues in their github, no one seems to have the same problem as mine, but people are having issues while using modelviewsets api. -
Create table on Reportlab the next row display above
I am new to reportlab for creating PDF and very confuse about x,y coordinate. When create the table on canvas, the second row insert above the first row instead. So, the data on table is overlap with above. How to fix it. Thank you advance. .. 4th 3rd row 2nd row 1st row -
Django-Streamlit integration
Can I integrate Streamlit with Django ? I tried but didn't know what to render ? I used the this code inside the django app -
Django filter two levels of DB relationships
I have three models that I'm trying to hook up so I can pull-out StudentItem information based upon ID of the Course that was passed in. The models look like the following: class Student(models.Model): first_name = models.CharField(max_length=128, unique=False) last_name = models.CharField(max_length=128, unique=False) class Course(models.Model): name = models.CharField(max_length=256, unique=False) course_student = models.ManyToManyField(Student) class StudentItem(models.Model): item_student = models.ForeignKey('Student',on_delete=models.CASCADE) description = models.CharField(max_length=256, unique=False, blank=True) Right now, my view looks like: class CourseDetailView(LoginRequiredMixin,DetailView): model = models.Course def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['student_item_list'] = StudentItem.objects.prefetch_related(Prefetch('item_student__id__course_student',queryset=Course.objects.filter(pk=self.kwargs['pk']))) return context I can get everything connected via prefetch across all of the models but the queryset filtering is not working. I am getting all records for every course regardless of the course ID that was passed in. Hopefully it's a small tweak. Really appreciate the help! -
customize signing key in drf-simplejwt
I want to customize the signing key to include tenant information. Right now the token generated is valid for all the tenants. This question has been already asked before but it is for flask and jwt-extended here. Is there anyway to do the same functionality in drf-simplejwt? SIMPLE_JWT = { ... 'SIGNING_KEY': SECRET_KEY, ... } In the documentation, they have provided that in the settings we can change it, but i want to change it based on the incoming request where i can get the tenant info in the url. If this is not the right approach please suggest if there is any other way to restrict jwt per tenant. -
How to check if an existing specific user (say techxhelp) is logged in and then logout that specific user in django?
I want to do something like this in views. This is not a perfect code. I am just giving an example of what is my requirement. def home(request): if request.user.techxhelp is_logged_in: logout(techxhelp) else: pass I tried searching Google and different sites but I found nothing. If anyone knows the solution, I shall be very thankful. -
Django: Set a dropdown form field to a value from the current detail view's Model
I have a little Django form that allows me to change the stage of an assessment. This is used by staff to keep the user and other staff members up to date on where they're at. Currently, I'm just loading the default option as what I have set as default in the model ("NEW"), I would prefer if this would instead select the option that the current model of the detail view page is actually set to, e.g. ("IN PROGRESS"). Screenshot below is what it currently displays. So if the stage is In Progress then on the page load, I would like this dropdown option to have already selected "In Progress". Is there any method either within the form widget settings, html template, or within Javascript to make this change? Forms.py class ChangeStageForm(ModelForm): class Meta: model = Assessment fields = ['assessment_stage', ] labels = { 'assessment_stage': _('Change Assessment Stage'), } Model Field with Choices ASSESSMENT_STAGE_CHOICES = [ ('NEW', 'New'), ('INPRO', 'In Progress'), ('WAIT', 'Waiting on Applicant'), ('CAN', 'Cancelled'), ('DEC', 'Declined'), ('COMP', 'Completed'), ] assessment_stage = models.CharField(max_length=21, choices=ASSESSMENT_STAGE_CHOICES, default='NEW') Template HTML Assessment Stage: {{ assessment.get_assessment_stage_display }} <form method="POST"> {% csrf_token %} {{ change_stage_form }} <button type="submit" name="change_stage" class="btn btn-success">Save</button> </form>