Login

Tag "django"

213 snippets

Snippet List

Mask sensitive data from logger

This will help to secure the sensitive secrets, token, api keys, etc from logger. As we know there is security issue when we include the sensitive information to the logger in case logger got leaked/hacked. Before: ``` INFO ('192.168.1.1', 33321) - "WebSocket /ssh?token=abcdefg&width=20&heigh20" ``` After: ``` INFO ('192.168.1.1', 33321) - "WebSocket /ssh?token=********&width=20&heigh20" ```

  • django
  • security
  • logging
  • logger
Read More

Django Standard API Response Middleware for DRF

As you can see, if you using django-rest-framework, you will found many different response format. This middleware to solve all of these problems with Standard API Response. All HTTP Response status stored into json response, not in HTTP Status (because mobile application, like android can't fetch the response body when HTTP Status >= 400).

  • middleware
  • django
  • api
  • django-rest-framework
Read More

Python Django CRUD Example Tutorial

Hey Friends, In this quick example, let's see django tutorial & crud example with mysql and bootstrap. step by step explain django crud operations with mysql backend. step by step explain django crud operations with mysql bootstrap. let’s discuss about django crud operations with mysql database. Read more... [https://tuts-station.com/python-django-crud-example-tutorial.html](https://tuts-station.com/python-django-crud-example-tutorial.html)

  • django
  • python
  • crud
Read More

Calculating Maintainability Index for a whole project

With this command you can calculate the maintainability index for your whole project. In your settings you have to add a dictionary called `RADON_MI_SETTINGS`. It could be like this: ```python RADON_MI_SETTINGS = { 'paths': ['projectname'], 'exclude': 'projectname/some_app/some_file.py', 'ignore': 'migrations,tests', } ``` I had to add following packages: ``` radon==3.0.1 progress==1.5 plotly==3.7.0 GitPython==2.1.11 ``` Following commands are available: * `python manage.py calculate_maintainability_index` Only display the maintainability index of the project. The average from every file is build by using the logical lines of code per file. * `python manage.py calculate_maintainability_index --init` Go through every commit filtered by their commit_message (is set to “bump version” currently) and calculate the maintainability index for the whole project. This creates a file with the history. * `python manage.py calculate_maintainability_index --showhistory` Display the history of the maintainability_index in a graph in your browser. * `python manage.py calculate_maintainability_index --commit` Calculate the current maintainability_index and append it to your history. Commit your edited history file. * `python manage.py calculate_maintainability_index --fail` Calculate the current maintainability_index and raise an Error, if it is lower than the last entry in your history. Useful for use in an automated pipeline. Hints: * radon has a problem with large lists and dictionaries. If you have a file with a list or dictionary with more than 100 entries, you should exclude it. * To initialize your history you should change the commitmessage filter to something, that suits your needs. Created by Martin Becker at [Jonas und der Wolf GmbH](https://www.jonasundderwolf.de)

  • django
  • command
  • git
  • maintainability
Read More

Signal to notify new saved comments

Signal to notify new saved comments. **Example:** from django.contrib.comment import models, signals signals.comment_was_posted.connect(new_comment_notifier, sender=models.Comment)

  • django
  • python
  • comments
  • signals
Read More

Django Online Now Users - Middleware

django online users, usage: `{{ request.online_now }}` or `{{ request.online_now_ids }}`, complete tutorial: https://python.web.id/blog/django-count-online-users/, this snippet forked from: https://gist.github.com/dfalk/1472104

  • middleware
  • django
  • session
  • cache
Read More

inline forms for deeply nested models

I had a problem trying to display my model would have a foreign key and that model would have one too etc. Now there was a point I wanted to display the foreign keys of that field and display its fields and so on so forth. This pretty much expands the models by getting the base form that worked best for me. It is intended to only work alongside `Forms`. I haven't been able to get it to work with `ModelForm`. Example usage: forms.py class AddressForm(forms.Form): address_0 = forms.CharField(label="address", max_length=64) address_1 = forms.CharField( label="address cont'd", max_length=64, required=False) city = forms.CharField(max_length=64) state = USStateField(widget=USStateSelect) # django_localflavor_us.forms zip_code = USZipCodeField(label='zipcode') # django_localflavor_us.forms class ContactInfoForm(ForeignKeyFormMixin, forms.Form): name = forms.CharField(max_length=50) # address = model.ForeignKey(Address) # is a foreignkey in my model for Address phone = PhoneNumberField() # phonenumber_field.formfields (irrelevant could very well be forms.CharField) fax = PhoneNumberField(required=False) # phonenumber_field.formfields (irrelevant could very well be forms.CharField) email = forms.EmailField() foreign_keys = {'address': AddressForm} # foreign forms I want to introduce, key acts as a related_name def __init__(self, *args, **kwargs): super(ContactInfoForm, self).__init__(*args, **kwargs) class GenerationForm(ForeignKeyFormMixin, forms.Form): company = forms.CharField(max_length=50) code = forms.CharField(max_length=50, required=False) # contact = model.ForeignKey(ContactInfo) # is a foreignkey in my model for Contact # facility_address = model.ForeignKey(AddressForm, related_name='facility') # is a foreignkey in my model for Address # mailing_address = model.ForeignKey(AddressForm, related_name='mailing') # is a foreignkey in my model for Address foreign_keys = {'contact': ContactInfoForm, 'facility_address': AddressForm, 'mailing_address': AddressForm} view.py def generation_create_view(self): if self.request.method == 'POST': generator_form = GenerationForm(self.request.POST) if generator_form.is_valid(): cleaned_data = generator_form.cleaned_data (contact_address, created) = Address.objects.get_or_create( address_0=cleaned_data['contact_address_address_0'], # notice naming. trying to keep it orgnized as possible and reuse the "foreign key" you want to expand address_1=cleaned_data['contact_address_address_1'], city=cleaned_data['contact_address_city'].title(), state=cleaned_data['contact_address_state'][:2].upper(), zip_code=cleaned_data['contact_address_zip_code'], ) print contact_address (contact_info, created) = ContactInfo.objects.get_or_create( name=cleaned_data['contact_name'], address=contact_address, phone=cleaned_data['contact_fax'], email=cleaned_data['contact_email'], ) print contact_info # ... # (assuming you have created other models as above) (generator, created) = Generator.objects.get_or_create( contact=contact_info, company=cleaned_data['company'], facility_address=facility_address, mailing_address=mailing_address, code=cleaned_data['code'], ) return redirect('to some where') else: generator_form = GenerationForm() return render(request, 'generation_create.html', {'generator_form': generator_form, }) generator_form.html # assuming your standard form tags are setup `<form class="form"...>...`. you would access form and display as follows # I am using https://django-bootstrap.readthedocs.io/en/latest/index.html # to help display forms in bootstrap <p class="lead">Contact</p> {% bootstrap_form generator_form.contact %} # can also just do {{ generator_form.contact }} {% bootstrap_field generator_form.company %} # can also just do {{ generator_form.company }} <p class="lead">Facility:</p> {% bootstrap_form generator_form.facility_address %} # can also just do {{ generator_form.facility_address }} <p class="lead">Mailing:</p> {% bootstrap_form generator_form.mailing_address %} # can also just do {{ generator_form.mailing_address }} {% bootstrap_field generator_form.code %} # can also just do {{ generator_form.code }}

  • django
  • django-forms
Read More

a better Django Slug Unique Generator

let say the user chooses the name "Elsa Frozen" now his slug would be "Elsa-Frozen-5" it means 4 other people have used the same header now he can go to url: "your website.com/Elsa-Frozen-4" to see other people's Post

  • django
  • slug
  • url
Read More

Read image url as base64

Read the image url as base64 in django, this snippet usefull if you using the `django-easy-pdf` to solve this issue https://github.com/nigma/django-easy-pdf/issues/53 Usage example: ``` <img src="{{ profile.photo.url|read_image_as_base64 }}"> ```

  • django
  • image
  • templatetags
  • base64
  • imagepreview
Read More