Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Stripe client_reference_id: null in checkout.session.completed
I have a stripe pricing table on my front end to render the options available to customers. On my backend I am using Django to handle account creation if the payment was successful. As below this was created following a tutorial on TestDriven.io btw. if event['type'] == 'checkout.session.completed': session = event['data']['object'] print(session) # # Fetch all the required data from session client_reference_id = session.get('client_reference_id') stripe_customer_id = session.get('customer') stripe_subscription_id = session.get('subscription') # Get the user and create a new StripeCustomer user = CustomUser.objects.get(id=client_reference_id) StripeCustomer.objects.create( user=user, stripeCustomerId=stripe_customer_id, stripeSubscriptionId=stripe_subscription_id, ) I am getting the following error raise self.model.DoesNotExist(apps.authentication.models.CustomUser.DoesNotExist: CustomUser matching query does not exist So after some digging I have found that Stripe is not returning the client_reference_id to my backend, below is a printout of the session variable "client_reference_id": null, I believe this is why the account is not being found by Django, but I can't seem to figure out why Stripe isn't sending this information over or how to attach it to the response to my Web hook? -
How to save mpesa transaction in my django app
I am currently working on a django app where I can be able to see and save all transaction made via my till number... No stk push just to be able to see and save all transaction done to that till number... Is there a way I can achieve that -
How to access(loop through) queryset passed from views to html template inside javascript block in django?
I want to loop through array/queryset passed from view to html template in django inside {% block js %} block, is it possible ? -
Weasyprint splits list marker from text on natural pagebreak
I have a styled ol item: <ol> <li>Communication requirements</li> </ol> CSS as follows: ol { list-style-type: none; counter-reset: item; margin: 0; padding: 0; } ol > li { counter-increment: item; font-weight: 700; display: table; margin-bottom: 10px; padding-top: 16px; } ol > li:before { content: counters(item, ".", decimal) ". "; display: table-cell; padding-right: 16px; } However when outputting to WeasyPrint there is a natural page break, the list marker is left behind: How do I prevent this? -
Custom Reset password templates forms doesn't show
I modified the first password reset page successfully. (Where the user insert his email address) Where it doesn't work it the Password Reset Confirm page (Where the users write his new password). When I click the link that I received by email to reset the password, it load my html template but it doesn't load my form. (Only load h1 tag and other things) html template {% load static %} <div class="box" align="center"> <h1>Write your new password</h1> <div class="small-line"></div> <form method="POST"> {% csrf_token %} {{ context.as_p }} <button type="submit" class="sendbut">Reset Password</button> </form> </div> forms.py class SetPasswordForm(forms.Form): def __init__(self, *args, **kwargs): super(SetPasswordForm, self).__init__(*args, **kwargs) # … new_password1 = forms.CharField( label=("New password"), widget=forms.PasswordInput(attrs={'autocomplete': 'new-password'}), strip=False, help_text=password_validation.password_validators_help_text_html(), ) new_password2 = forms.CharField( label=("New password confirmation"), strip=False, widget=forms.PasswordInput(attrs={'autocomplete': 'new-password'}), ) views.py @sensitive_post_parameters() @never_cache def PasswordResetConfirmView(request, uidb64=None, token=None, template_name='users/password_reset_confirm.html', token_generator=default_token_generator, set_password_form=SetPasswordForm, post_reset_redirect=None, current_app=None, extra_context=None): """ View that checks the hash in a password reset link and presents a form for entering a new password. """ UserModel = get_user_model() assert uidb64 is not None and token is not None # checked by URLconf if post_reset_redirect is None: post_reset_redirect = reverse('password_reset_complete') else: post_reset_redirect = resolve_url(post_reset_redirect) try: # urlsafe_base64_decode() decodes to bytestring on Python 3 uid = force_str(urlsafe_base64_decode(uidb64)) user … -
Django: TextChoices appearing in array as the __str__ representation and not as the value
I have the following field in my model: schedule = models.CharField( choices=WorkScheduleType.choices, max_length=255, unique=True, ) This behaves as expected when I do something like this: print(schedule) > DAILY But when I do something like this: print([schedule]) It renders like this: ["WorkScheduleType<DAILY>"] Why is this? Is the proper way to do this really in two lines instead? my_array = [] my_array.append(schedule) print(my_array) -
How do I use Javascript eventListeners in Django project
I am pretty much new to the Django framework and working on a small project that requires me to use static files (JavaScript) in it. I have a couple of buttons that I want to manipulate from the DOM but for some reason, I cannot have access to these buttons using DOM manipulations. Can someone please tell me why I can't print these buttons in my console? What I get an an output is an empty HTMLcollection[] const deleteButton = document.getElementsByClassName('delete-button'); console.log(deleteButton); ** Template ** <div class="my-2"> {% for todo in mytodos %} <div class="checkbox my-2"> <div class="checkbox-wrapper"> <input type="checkbox" id="cbox3" class="mr-2" value="third_checkbox"> <label for="cbox3"> {{ todo.todotext }} </label> </div> <div> <a href= {% url 'delete' %}> <button class="delete-button btn btn-outline-danger">Delete</button> </a> </div> </div> {% endfor %} </div> -
Django convert timestamp before performing a query?
I have a unique instance where my front-end timestamp is generated based off of a user specific setting. (User can choose their timezeone, 12/24 hour clock). I have a search feature in which a user can search based off of a timestamp. The issue that I have is that my timestamp in the database is a UTC timestamp, but the user will want to search based off of the visual timestamp that they see on the page. For example on the front-end of my application the timestamp shows... 2022-09-21 8:25:26 a.m. Yet on the postgres side that timestamp will show as... datetime.datetime(2022, 9, 21, 12, 25, 26, 959035, tzinfo=datetime.timezone.utc) When a user types in 09-21, as expected, zero results get returned. I am looking for a way to do convert time timestamp to the users timestamp before the query takes place, but not sure on the best solution, or right direction to to here. Any guidance would be greatly appreciated! -
Data upload server with user management and resumable uploads
I’m looking to build a web-based data upload server for a citizen science project and am wondering if there are out-of-the box solutions available or if there are some useful Python packages, libraries available to make the job easier? I don’t really want to reinvent the wheel and it seems that something like this should already exist. Maybe I’m just looking in the wrong place. The brief is that our volunteers make audio recordings to monitor threatened species, then upload their data for archiving and automated processing. I’d like a server that has the following: Simple web-based user interface - many of our participants have limited confidence with computers; No client-side software to install; User management: registration to approved email addresses only (or similar, maybe a manual admin approval process); Data files are 1 to 40MB in size but there are lots of them ~1000 files, and ~10 GB in total. If user loses network connection, uploads should be recoverable with the server capable of resuming an upload where it left off. That's quite important. live progress and status updates to the user. I have access to a web hosting server. Maybe a Django or Flask implementation already exists, or … -
Python Django M2M attribute via an intermediary model
I have a model with 2 M2M attributes: Connection is recursive and the ConnectionRequest uses an intermediary class. With Connection attribute, I am able to retrieve the connections of a user without problems (since I am using a native M2M field). But with ConnectionRequest is where I have challenges. I would like to retrieve the 'connection requests' for this user but struggling with this natively. I have implemented it however programmatically (through a query) - but its not clean. Basically, I would like to return the list of all connection requests. ie where the recipientAccount is the same as the parent class (Account) object. class Account(models.Model): firstName = models.CharField( 'First Name', max_length=100, blank=True, null=True) lastName = models.CharField( 'Last Name', max_length=100, blank=True, null=True) emailAddress = models.EmailField( 'Email Address', max_length=255, blank=True, null=True, unique=True) connections = models.ManyToManyField('self', blank=True) connection_requests = models.ManyToManyField( 'ConnectionRequest', blank=True, related_name='accounts') def __str__(self): return self.firstName + ' ' + self.lastName class ConnectionRequest(models.Model): senderAccount = models.ForeignKey( Account, related_name='sender_Account', on_delete=models.CASCADE) recipientAccount = models.ForeignKey( Account, related_name='recipient_Account', on_delete=models.CASCADE) def __str__(self): return str(self.senderAccount.id) + ' to ' + str(self.recipientAccount.id) I have an idea to try the below but suddenly realised that I am unable to access the Account object from the ConnectionRequest class (since its … -
How i can use nested include and block tag in django templates?
I want to show list of books in page. But below code does not do it. base.html <!DOCTYPE html> <html lang="en"> <head> </head> <body> {% include 'core/main.html' %} </body> </html> main.html <main class="container"> <div class="wrapper"> {% block main %} {% endblock %} </div> </main> books.html {% extends 'core/base.html' %} {% block main %} Books {% endblock %} -
Two different forms on one $(document).ready(function) submit
I have two different forms which basically do the same thing so just for an ease of use and less coding is there any way I can assign both of them on one $(document).ready(function()). My original $(document).ready looks like this : $(document).ready(function() { $("#transaction_form_new").on('submit', (function(e) { e.preventDefault(); var formData = new FormData(this); formData.append('farm', {{farm.id}}); $.ajax({ ... }) This one is for creating a new form and i want to add the 'edit_form' also. I tried it like this but with no result: $(document).ready(function() { $("#transaction_form_new"),$("#transaction_form_edit").on('submit', (function(e) { -
Group records in queryset
I have the following models in an django app. class Person(models.Model): name = models.CharField(max_length=50) class Product(models.Model): owner = models.ForeignKey(Person, on_delete=models.CASCADE) class Order(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) buyer = models.ForeignKey(Person, on_delete=models.CASCADE) I would like to get a list of orders placed by a buyer grouped according to the owner of the product in the order. Something like this orders placed by buyer 1 order__product__owner 1 order 1 order 2 order 3 order__product__owner 2 order 4 order 5 order 6 -
how to dynamically populate choices field from another model containing the values to be used - Django
I have a model that has some choices that the admin chooses while entering some data in the admin pannel. I am using the general way of making a choice field as below CATEGORY= ( ('arbitration', 'arbitration'), ('binding precedent', 'binding precedent'), ('contempt', 'contempt'), ('execution of decree', 'executuon of decree'), ('limitations', 'limitations'), ('negative equality', 'negative equality'), ('od/ss/rd', 'Obitor Dicta / Sub Silenso-Ratio/ Decidendi'), ('review', 'review'), ('special relief', 'special relief'), ) ) class Civil(models.Model): law_category= models.CharField(max_length=60, choices=CATEGORY ,null=True, help_text="required") Here the choices are hard coded. Now I want the admin to have control over what choices he can have inside CATEGORY. So what I thought would work is to create another model where he can enter the the values for CATEGORY and that would in return create some dynamic choices for the field law_category= models.CharField(max_length=60, choices=CATEGORY ,null=True, help_text="required") The way I approached the problem was as below class CivilChoices(models.Model): key=models.CharField() value = models.CharField() Here I thought of entering the key and values. But now I do not know how to get these values inside the Civil model for CATEGORY to use, or even if it is the right way to do it. Please suggest me a way to create dynamic choices for … -
Django LEFT JOIN or INNER JOIN the same query set together multiple times
It's been a minute since I've used SQL so I'm not 100% sure LEFT or INNER join is the correct term, as I googled this and in most cases, people just wanted to concatenate the results, wich is not SQL JOIN's. I have 3 models. Dumbed down they are as follows: class Stakeholders(models.Model): firstname = models.CharField(max_length=50) lastname = models.CharField(max_length=50) email = models.EmailField(max_length=254) class Policy(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=150) class StakeholderPolicyResp(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) stakeholder = models.ForeignKey(Stakeholders, on_delete=models.CASCADE) policy = models.ForeignKey(Policy, on_delete=models.CASCADE) response = models.IntegerField(default=0) I want to create a table that has a unique stakeholder with the response for up to 4 policies. In simple example: Stakeholder ------------------- 1 John Doe jd@email.com Policy ------------------- 1 Policy 1 2 Policy 2 3 Policy 3 StakeholderPolicyResp ------------------- UID1 1 1 0 UID2 1 2 4 UID3 1 3 3 What I want out is a table that can have varying amount of columns, but something like this: MyTable ------------------ Stakeholder data - Policy x Resp - Policy y Resp - Policy z Resp ================== John | Doe | 0 | 4 | 3 Here we have the stakeholder with the responses for policy 1, policy 2 and policy … -
How to make a filter in a model (Django/ORM) respecting the place of the fields in the query?
I have a model Student with this fields: id, first_name, last_name. I added a compose index with first_name and last_name. The problem is when i filter. I use Student.objects.filter(last_name='Caicedo', first_name='Pedro') but the internal ORM select is: SELECT `students`.`id`, `students`.`first_name`, `students`.`last_name` FROM `students` WHERE (`students`.`first_name` = 'Pedro' AND `students`.`last_name` = 'Caicedo'); args=('Pedro', 'Caicedo'); It does not respect the order, and I need to respect it by optimizing the query. -
Django Admin and object ID = 0
Using django admin to manage records from a pre-existing external database, I face issues with objects having 0 as value for the model's id fields. Each time i edit this object django creates a new one. I understand that having 0 for an id is like having a null value and that django considers the object as a new one to be inserted in the model table. is there a way to specify that 0 is a good id (even if not a good idea ...) ? -
How to override create action of django rest framework ModelViewSet to create bulk records?
Demo model class Item(models.Model): name = models.CharField(max_length=20) Demo view class ItemViewSet(viewset.ModelViewSet): queryset = Item.objects.all() serializer_class = ItemSerializer Demo input passing using API post request [ {name: 'Book'}, {name: 'PC'}, {name: 'Phone'} ] How to create multiple table records with single post request? -
UndefinedColumn column integrations_externalrecord.oppcontact_id does not exist django postgresql
When accessing my ExternalRecord model via the django admin screen, or by querying ExternalRecord.objects.all(), I receive the error: psycopg2.errors.UndefinedColumn: column integrations_externalrecord.oppcontact_id does not exist I am building an integration functionality, and we have a junction table that houses an external id and the instance in our database that corresponds to this external id, set up like so: class ExternalRecord(UUIDPrimaryKey, CreatedModifiedMixin, models.Model): integration = models.ForeignKey( to=Integration, related_name='external_records', on_delete=models.CASCADE ) emailuser = models.ForeignKey( "accounts.EmailUser", related_name='external_records', null=True, blank=True, on_delete=models.CASCADE ) institution = models.ForeignKey( "institutions.Institution", related_name='external_records', null=True, blank=True, on_delete=models.CASCADE ) oppcontact = models.ForeignKey( "opp_contacts.OppContact, related_name='external_records', null=True, blank=True, on_delete=models.CASCADE ) external_record_id = models.CharField( max_length=1000 ) and so on... When I view the OppContact model either by viewing in the django admin screen or with OppContact.objects.all(), I see that the model has a field for "id". When I rollback to the migration before applying the oppcontact field, everything returns to work as normal, meaning I can query/view ExternalRecords without getting an error. This is my OppContact model: class OppContact(UUIDPrimaryKey): company = models.ForeignKey( "accounts.Company", on_delete=models.CASCADE, blank=True, null=True ) first_name = models.CharField( max_length=100 ) last_name = models.CharField( max_length=100 )... And this is another model to which my ExternalRecord can be linked, Institution: class Institution(UUIDPrimaryKey, CreatedModifiedMixin, models.Model): company = … -
InMemoryUploadedFile is not JSON serializable
I'm sending a payload with some string and two images in a POST Request. But I'm not sure how to serialize the images in the payload. I'm using POSTMAN's form-data to send this request and I'm getting ('Object of type InMemoryUploadedFile is not JSON serializable') def registration(self, payload): try: headers = {"accept": "application/json"} logger.debug({"payload": payload}) response = requests.post(url=self.registration_url, headers=headers,json=payload) if response is None: return None, status.HTTP_424_FAILED_DEPENDENCY parsed_data = data_parser.render_registration_response(response, payload) return parsed_data, response.status_code except Exception as e: logger.error(repr(e)) return None, status.HTTP_424_FAILED_DEPENDENCY Serializers.py class RegistrationSerializer(serializers.Serializer): name = serializers.CharField(max_length=20) vehicle_number = serializers.CharField(max_length=50) blue_book = serializers.ImageField(max_length=None, allow_empty_file=False, required=False) vehicle_class = serializers.CharField(max_length=50) bank_account = serializers.CharField(max_length=50) phone = serializers.CharField(max_length=20) avatar = serializers.ImageField(max_length=None, allow_empty_file=False, required=False) country = serializers.CharField(max_length=20) state = serializers.CharField(max_length=20) city = serializers.CharField(max_length=20) zip = serializers.CharField(max_length=20) -
Add attribute to the checkbox field based on initial django form
class MyForm(Form): real = BooleanField() If MyForm(data={'real': 'on'}), I want to render <input type="checkbox" checked=checked data-initial='on'>. If MyForm(data={}), I want to render <input type="checkbox">. How to achieve this? -
Import images from excell file to django database
I am looking for some code to import all images from excel sheet and save them in my database without using pywin32. Any help would be grateful. Thanks -
ValueError: source code string cannot contain null bytes in django anytime i run mange.py
I am having issues with my django project, Anytime i run the manage.py command line. It gives out this error main() File "/storage/emulated/0/django/twitter/manage.py", line 21, in main execute_from_command_line(sys.argv) File "/data/data/com.termux/files/home/my_venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line utility.execute() File "/data/data/com.termux/files/home/my_venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 369, in execute settings.INSTALLED_APPS File "/data/data/com.termux/files/home/my_venv/lib/python3.10/site-packages/django/conf/__init__.py", line 84, in __getattr__ self._setup(name) File "/data/data/com.termux/files/home/my_venv/lib/python3.10/site-packages/django/conf/__init__.py", line 71, in _setup self._wrapped = Settings(settings_module) File "/data/data/com.termux/files/home/my_venv/lib/python3.10/site-packages/django/conf/__init__.py", line 179, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/data/data/com.termux/files/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 879, in exec_module File "<frozen importlib._bootstrap_external>", line 1017, in get_code File "<frozen importlib._bootstrap_external>", line 947, in source_to_code File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed ValueError: source code string cannot contain null bytes I have tried other solutions online and it is not working. Please could anyone help me. This is my setting file -
How to validate unique roll number and show them a validation error when the roll already exists using serializers Django Rest framework
I want to validate roll number in Serializers Django Rest framework I want to show validation error when the roll number is already present in the database. -
DRF: Is there any way to keep ModelSerializer's auto-generated validators while using dynamic fields?
I'm trying to have Django Rest Framework serializers with dynamic fields that depend on the context passed (request method, CRUD action etc.). So I set the fields in self.fields when the serializer is initialized. It works fine at the moment, but the problem is that I don't get the automatically generated validators that ModelSerializer provides. Is there any way to get those validators or do I have to resort to copy pasting validators from my models?