Showing posts with label Django. Show all posts
Showing posts with label Django. Show all posts


 class MainSerializer(serializers.ModelSerializer):

deatils= serializers.SerializerMethodField() class Meta: model = Tag fields = ["id", "name", "deatils"] def get_deatils(self, obj): if obj.user_type == "public": return PublicUserSerializer(obj.prefetch_user, many=True).data else: return AdminUserSerializer(obj.prefetch_user, many=True).data

 

Using multiple model in django form

Posted In: , . By CreativeSolutions


 To use profile model with user form we need to initialize the form fields in the form. Then to get the values on edit we need to initialize __init__ function and passing the profile object from the view

 Ex: forms.py
 class SuperUserEditForm(forms.ModelForm):
    birthday = forms.DateTimeField(input_formats=['%Y-%m-%d %I:%M %p'], required=False)
    phone_number = forms.CharField(max_length=100, required=False, label="Home Phone")
    cell_number = forms.CharField(max_length=100, required=False)
    carrier = forms.ChoiceField(choices=CARRIERS, required=False)
   
    def __init__(self, profile=None, *args, **kwargs):
        super(SuperUserEditForm, self).__init__(*args, **kwargs)
        if(profile):
            self.fields['cell_number'].initial = profile.cell_number
            self.fields['carrier'].initial = profile.carrier
            self.fields['birthday'].initial = profile.birthday
            self.fields['phone_number'].initial = profile.phone_number

 Ex: views.py
     form = SuperUserEditForm(profile=profile, instance=user)

     on POST
     form = SuperUserEditForm(data=request.POST, instance=user)

 

Csv upload and import in python django

Posted In: , . By CreativeSolutions


 if request.method == 'POST':
        srcfile = request.FILES.get("file", None)
        reader = csv.DictReader(srcfile) # read rows into a dictionary format
        for row in reader:
   print row

 

How to show django cursor execute query

Posted In: . By CreativeSolutions


 We can use the variable _executed with the cursor object ie. cursor._executed

 cursor = connection.cursor()
 cursor.execute(sql, (params))
 print cursor._executed
 rows = cursor.fetchall()

 

Using for loop counter in django template

Posted In: . By CreativeSolutions


 Django has the function forloop.counter to use the index for the row in template

 Ex:
 {% for question in questions %}
{{ forloop.counter }}
  {% endfor %}

 

Get python django model choice in View

Posted In: , . By CreativeSolutions


Suppose you have a model

 class User(models.Model):

   TYPES = (
('Admin', 'Admin'),
('Staff', 'Staff'),
  )


 You can access this in the view using the following code

 In your view file

 from app.core.models import User

 def save(request):
     user_types = User.TYPES

    render('user/form.hrml', {user_types:user_types})

If you want to use this variable in the template, Assign that value user_types as a dictionary variable then use the below code
{% for value, text in user_types %}
{{ value }} {{ text }}
{% endfor %}


 

How to show all the form errors in django form

Posted In: . By Webdevelopmentlogics


{% if my_form.errors %}

div id="errors"
div class="inner"
There were some  errors in the data you entered. Please correct the following
{{ my_form.non_field_errors }}
ul
{% for field in my_form %}
{% if field.errors %}li{{ field.label }}: {{ field.errors|striptags }}/li{% endif %}
{% endfor %}
/ul
/div
/div

{% endif %}

 

Django query with list of values in where clause

Posted In: , . By CreativeSolutions


If we need to fetch data like the MySQL IN clause, we can do it by using filter function with the list of values
user_ids= [1,2,3]
Ex. User.objects.filter(id__in = user_ids)

 


import time

Then add the below code
#Finding the daylight saving time
    is_dst = time.daylight and time.localtime().tm_isdst > 0
    utc_offset = (time.altzone if is_dst else time.timezone)
#Checking for negative and positve offset values
    if(utc_offset > 0):
        utc_offset_hours = (utc_offset / 3600)
        sign = '- '
    else:
        utc_offset_hours = (-(utc_offset) / 3600)
        sign = '+ '
    utc_offset_minutes =  (utc_offset % 3600) / 60
#Converting Integer values to string before concatenating
    utc_offset = sign + str(utc_offset_hours) + '.' +str(utc_offset_minutes)
    print utc_offset

 

Install new python package in virtualenv

Posted In: , . By Webdevelopmentlogics


  1. Enable virtualevn using command 'soure bin/activate'
  2. Then try the command 'echo $PATH' to show it's path. Then it will show the path with like given below
     /var/path/virtauanenv/bin
  3. Go the the package folder which you want to install. Then use the below command
     /home/user/package/folder$ /var/path/virtauanenv/bin/python setup.py install

 







 The below code can be used to count the number of male/female in the Profile

 Profile.objects.values('gender').annotate(gener_count=Count('gender'))

 


class MyForm(forms.ModelForm):
    OPTIONS = (
        ("IN", "India"),
        ("US", "United States"),
          )
    countries = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, label = "Select Medications", choices=OPTIONS)
#To change the order use the below code
    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields.keyOrder = ['name', 'countries', 'states']

    class Meta:
            model = MyModel

 

How to use group by clause to fetch related data

Posted In: . By CreativeSolutions


There is no exact group by clause and we can use the function annotate to get the count of records with grouping data.

   If we need to fetch the related data from 2 tables,
    first we need to fetch the unique data from first table
    then we can use the filter function with id__in

  ex:    
    mapdata = MedicationMapping.objects.all()
    meds = Medication.objects.filter(id__in=mapdata)

 

How to do add pagination in django framework

Posted In: . By Webdevelopmentlogics


In views.py add the below code
  d = FlatPage.objects.all() // Flatpage is the Model class
    paginator = Paginator(d, 2) # Show 2 help on each row
    page = request.GET.get('page')
   
    try:
        helps = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        helps = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        helps = paginator.page(paginator.num_pages)
    return render_to_response("flatpages_plus/list.html",{
            "data": helps }, RequestContext(request),
        )

In the template add teh following code

 div class="pagination"
         

                {% if data.has_previous %}
                 
  • previous

  •             {% endif %}
                {% if data.page_range_data.show_first %}
                 
  • 1

  •             {% endif %}
                {% for i in data.page_range_data.page_range %}
                    {% ifequal i data.number %}
                        {{ i }}
                    {% else %}
                       
  • {{ i }}

  •                 {% endifequal %}
                {% endfor %}
                {% if data.page_range_data.show_last %}
                   
  • {{ data.paginator.num_pages }}

  •             {% endif %}
                {% if data.has_next %}
                   
  • next

  •             {% endif %}
               

        /div

 

helpful links to learn django forms

Posted In: . By CreativeSolutions
 


1. Install virtualenv by dowloading or using the command 'yum install virtualenv' in terminal
 2. Then in the project's folder, run the command
     virtualenv [name] ex: venv
    with this you can add -no-site-packages or other options
 3. Then install django and necessary module in it.
 4. from the 'venv' directory created on executing the command 'virtualenv'
    run the command 'source bin/activate' in terminal
 5. run the command 'deactivate' from terminal to exit

 

How to set and print views variables in template

Posted In: . By CreativeSolutions


In the view
    return render(request, 'admin/user/form.html', {'form': form,'error_msg': error_msg})
In the template
    form action="" method="post">{{ form.as_p }}
    input type="submit" value="Save" /
    /form
    {% if error_msg %}
        {{ error_msg }}
    {% endif %}

 

Common field types in django models

Posted In: . By CreativeSolutions


OneToOneField
    - models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE)(SET_NULL, SET_DEFAULT)
ManyToManyField
    - models.ManyToManyField(Group, related_name='profiles', blank=True, null=True)
    - models.ForeignKey(User, related_name='+', on_delete=models.CASCADE) - no backward relation on setting related_name to +
CharField
    - CharField(max_length=100, blank=True, null=True, choices=CARRIER_CHOICES, default=CARRIER_CHOICES[-1][0])
    -
EmailField
    - models.EmailField(max_length=255, blank=True, null=True)
ImageField
    - models.ImageField(blank=True, null=True, upload_to=settings.UPLOAD_ROOT)
DateField
    - models.DateField(blank=True, null=True)
    - models.DateTimeField(auto_now_add=True)  - for saving new date
    - models.DateTimeField(auto_now=True) - for last modified time
    - models.TimeField()
URLField
    - models.URLField(max_length=255, blank=True, null=True)
BooleanField   
    - models.BooleanField(default=True)
IntegerField   
    - models.IntegerField(default=0)   

 

Set not null validation in django form

Posted In: . By CreativeSolutions





To set the not null validation, we need to set the 'Blank=False' in the corresponding field declaration in model
 
  Ex:
      name = models.CharField(max_length=255, blank=False, null=True)
     
      In this null=True refers to the database property

 

How to debug sql query in django

Posted In: . By Webdevelopmentlogics


  We can debug the django query using the 'print' command and look the terminal wher you alrady run the command 'python manange.py runserver'
  Ex:
       destination = Destination.objects.get(id = destId)
     print destination