Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
- 
        
Django Model not saving to MySQL (Maria DB) while others do
My app (Django v 2.2.5) is using MySQL (MariaDB 10.4.6) to store data in its database and has all migrations made and committed. It creates the superuser, when I log in I can creates all related objects, but the Product (arguably most important) is not being made. I click save and it does nothing. I have tried changing the model, and even removing the BooleanField (only unique field different from the models that are storing) and applying the migration but it still does not work. I even deleted the whole database and started anew in hopes of getting around any tricky migrations but that still did nothing for me. Here is my models.py: class Partner(models.Model): name = models.CharField(max_length=150, blank=False, help_text="Enter the vendor name", verbose_name="Vendor name", unique=True) address = models.TextField(help_text="Enter the address of the vendor") formula = models.ForeignKey(Formula, on_delete = models.CASCADE) phone = PhoneNumberField(help_text="enter the vendor phone number") email = models.EmailField(max_length=254, help_text="Enter the vendor email address") photo = models.ImageField(upload_to="vendors") def __str__(self): return self.name class ProductType(models.Model): name = models.CharField(max_length=150, blank=False, help_text="Enter the kind of product this is", verbose_name="Product type") def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=150, blank=False, help_text="Enter the name of the product", verbose_name="Product name") price = models.DecimalField(max_digits=12, decimal_places=5,\ help_text="Enter … - 
        
After import function is called 2 times
Hi I am importing a file and I want to delete all the data which is not in CSV file but present on DB so each time the CSV data is in the DB. Old data will be removed. def after_import_instance(self, instance, new, **kwargs): """ For each row in the import file, add the pk to the list """ if instance.pk: self.imported_rows_pks.append(instance.pk) def after_import(self, dataset, result, using_transactions, dry_run=False, **kwargs): """ delete all rows not in the import data set. Then call the same method in the parent to still sequence the DB """ ids = list(set(self.imported_rows_pks)) Product.objects.exclude(pk__in=ids).delete() import_export.resources.ModelResource.after_import(self, dataset, result, using_transactions, dry_run, **kwargs) My code is running 2 times can you help me on it. I think the function called one time when confirm import is triggered. - 
        
Django upgrading unsalted MD5 password not matching
I am migrating an old system that uses unsalted MD5 passwords (the horror!). I know Django handles automatically password upgrading, as users log in, by adding additional hashers to the PASSWORD_HASHERS list in settings.py. But, I would like to upgrade the passwords without requiring users to log in, also explained in the docs. So, I've followed the example in the docs and implemented a custom hasher, legacy/hasher.py: import secrets from django.contrib.auth.hashers import PBKDF2PasswordHasher, UnsaltedMD5PasswordHasher class PBKDF2WrappedMD5PasswordHasher(PBKDF2PasswordHasher): algorithm = "pbkdf2_wrapped_md5" def encode_md5_hash(self, md5_hash): salt = secrets.token_hex(16) return super().encode(md5_hash, salt) def encode(self, password, salt, iterations=None): md5_hash = UnsaltedMD5PasswordHasher().encode(password, salt="") return self.encode_md5_hash(md5_hash) and add it to settings.py: PASSWORD_HASHERS = [ "django.contrib.auth.hashers.PBKDF2PasswordHasher", "legacy.hashers.PBKDF2WrappedMD5PasswordHasher", ] However, testing this in the Django shell check_password is returning False for the upgraded password. >>> from django.contrib.auth.hashers import check_password, UnsaltedMD5PasswordHasher >>> from legacy.hashers import PBKDF2WrappedMD5PasswordHasher >>> hasher = PBKDF2WrappedMD5PasswordHasher() >>> test_pwd = '123456' >>> test_pwd_unsalted_md5 = UnsaltedMD5PasswordHasher().encode(test_pwd, salt='') >>> print(test_pwd_unsalted_md5) '827ccb0eea8a706c4c34a16891f84e7b' # this is an example of a password I want to upgrade >>> upgraded_test_pwd = hasher.encode_md5_hash(test_pwd) >>> print(upgraded_test_pwd) pbkdf2_wrapped_md5$150000$f3aae83b02e8727a2477644eb0aa6560$brqCWW5QuGUoSQ28YNPGUwTLEwZOuMNheN2RxVZGtHQ= >>> check_password(test_pwd, upgraded_test_pwd) False I've looked into other similar SO questions, but didn't found a proper solution there as well. - 
        
How to prevent a url from changing when loading the same template with different data in Django
I got a simple def with something like this def policies_index(request): """Resource listing""" policies = Policy.objects.all() context = { 'policies' : policies } return render(request, "policies/index.html", context) now I want to add a way to filter that info using month and year so I made a function like this def policies_date_filter(request): """List the resources based on a month year filter""" today = datetime.date.today() year = request.POST['year'] month = request.POST['month'] policies = Policy.objects.filter(end_date__year=year).filter(end_date__month=month) status = settings.POLICY_STATUS_SELECT for policy in policies: for status_name in status: if status_name['value'] == policy.status: policy.status_name = status_name['name'] request.policies = policies return policies_index(request) that way I can reuse the function index to avoid writing the code to print the view again and works perfect, but in the url instead of something like "/policies" I got something like "/policies/date-filter" Which makes sense since Im calling another function Is there a way to prevent the url from changing? - 
        
custom Django Management commad
The idea is to delete object by accepting command line options: object can be deleted by ID and by date range Expected behavior, new custom command call using: python manage.py delete_obj --delete id 1234 or python manage.py delete_obj --delete from 2019/10/01 to 2019/12/12 code for first part: from django.core.management.base import BaseCommand from ...models import SomeObject class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('id', type=int) parser.add_argument( '--delete', default = False, help='Delete product', ) def handle(self, *args, **options): if options['delete']: if options['id']: SomeObject.delete() I add custom option in the add_arguments() method for id, how I can define that object can be deleted by ID or by DATE RANGE - 
        
Saving React date picker data in Django
I use react-datepicker in React side and try to save that date to Python. The error I get is: time data '2019-12-12T12:45:37.910Z' does not match format '%Y-%m-%dT%H:%M:%S:%fZ' Here's how I try to convert in Django side: event_date = body["event_date"] date = datetime.datetime.strptime(event_date, "%Y-%m-%dT%H:%M:%S:%fZ").date() Here's my date field in python: event_date = models.DateField(auto_now=False, default=None, null=True, blank=True) ...and here's my Datepicker in React: const [eventDate, setEventDate] = React.useState(new Date()); .... .... <DatePicker selected={eventDate} onChange={setEventDate} showTimeSelect timeFormat="HH:mm" timeIntervals={15} timeCaption="time" dateFormat="yyyy-MM-dd hh:mm" /> I'm both OK to save date information as "2019-12-12 12:45" or save the timezone data. - 
        
How to select_related on an inherited table
I have a model that represents a Post model in django and one called NewsArticle which inherits from it. I also have a table of likes that maps a user's like to a Post. How can I get all NewsArticles with their corresponding like status? Here are the models I have: class Post(models.Model): title = CharField(max_length=200) content = TextField() def __str__(self): return self.title class NewsArticle(Post): link = URLField(default='') external_id = CharField(unique=True, max_length=50, help_text='The ID of the news article from the source') source = CharField(max_length=15, help_text='Name of source website') class Like(models.Model): LIKE_CHOICES = [('L', 'Like'), ('D', 'Dislike')] user = ForeignKey(User, on_delete=models.CASCADE) post = ForeignKey(Post, on_delete=models.CASCADE, related_name='post') state = CharField(default='L', max_length=1, choices=LIKE_CHOICES) created_at = DateTimeField(auto_now_add=True) updated_at = DateTimeField(auto_now=True) def __str__(self): return self.get_state_display() The query I'm trying should select from NewsArticle and have the state of the like of a user or None if no mapping exists. I tried to select_related('post_ptr') but that just added the post ID in the queryset which I don't really know how to use. - 
        
How to display properties of a nested object in Django Rest Framework
I am using Django and Django-Rest-Framework to build an API for a battle system. In my code, I have 2 models: A parent model Battle and a child model Round. Round has some @property fields (start_time, end_time, score) which are calculated based on different values. When I access the Round route directly, I get the desired output: http://127.0.0.1:8001/battle/rounds/1/ { "id": 1, "battle": "http://127.0.0.1:8001/battle/battles/1/", "index": 0, "contender_entry": null, "opponent_entry": null, "start_time": "2019-12-11T17:38:00Z", "end_time": "2019-12-11T17:39:40Z", "score": [ 0, 0 ] } however when I access the Battle route, the nested Rounds are returned, but only the database fields, not the properties: http://127.0.0.1:8001/battle/battles/1/ { "url": "http://127.0.0.1:8001/battle/battles/1/", "id": 1, "status": "live", "start_time": "2019-12-11T17:38:00Z", "round_length": "00:01:40", ... "rounds": [ { "url": "http://127.0.0.1:8001/battle/rounds/1/", "beat": null, "index": 0, "battle": "http://127.0.0.1:8001/battle/battles/1/", "contender_entry": null, "opponent_entry": null }, { "url": "http://127.0.0.1:8001/battle/rounds/2/", "beat": null, "index": 1, "battle": "http://127.0.0.1:8001/battle/battles/1/", "contender_entry": null, "opponent_entry": null }, { "url": "http://127.0.0.1:8001/battle/rounds/3/", "beat": null, "index": 2, "battle": "http://127.0.0.1:8001/battle/battles/1/", "contender_entry": null, "opponent_entry": null } ], "current_round": null } I want the properties to be displayed in the nested Round objects in Battle. But I couldn't get it to work. These are my models: class Round(models.Model): battle = models.ForeignKey(Battle, on_delete=models.CASCADE, related_name="rounds") index = models.IntegerField() contender_entry = models.OneToOneField(Entry, on_delete=models.DO_NOTHING, related_name="round_contender", … - 
        
How to create table in admin site members without reference
How to create table in admin site members without reference class Mas_Members(models.Model): ID = models.UUIDField(primary_key=True, null=False, default=uuid.uuid4, editable=False, serialize=True) MemberName = models.CharField(max_length=100) RegMethod = models.CharField(max_length=10, choices=C_RegMethod) RegID = models.CharField(max_length=20, blank=True) DeviceOS = models.CharField(max_length=10, choices=C_DeviceOS) DeviceID = models.CharField(max_length=30) NotiID = models.CharField(max_length=30) ImageFile = models.CharField(max_length=20) CountryCode = CountryField(blank_label='(select country)') LangCode = models.CharField(max_length=2) BirthYear = models.DateField() Gender = models.CharField(max_length=1, choices=C_Gender) RegisterDate = models.DateTimeField(editable=False) CurLatLocation = models.IntegerField(blank=True) CurLongLocation = models.IntegerField(blank=True) LastUpdate = models.DateTimeField(default=timezone.now) - 
        
Add metadata to WSGIRequest object
I have Django1.9 middleware class: class MyMiddleware(object): def process_request(self, request): token = self._get_or_create_token(request) #request.context['token'] = token The issue is: - I would like to put token to some sort of context to pass it through the application flow. - I avoid putting it into request session, because it result in extra database reading/writing. Could you suggest me some solution? - 
        
How to pass Audio file from model to Template in Django?
I've just started out with Django and have tried making an audio player application website. I (admin) want to be able to upload audio files that visitors can listen to. I've created a model for succesfully uploading a file, taking a input file name, and storing it in a media folder in within my app directory: class Song(models.Model): name = models.CharField(max_length=125) audio_file = models.FileField(upload_to='audio_player/media/audio_player/') def __str__(self): return self.name In my Template I then have a for loop set up to create list of audio players for every different audio track.: <div class="container"> {% for song in songs %} <audio controls id="player"> <source src="{{ song.audio_file.url }}" type="audio/wav"> </audio> {% endfor %} </div> Now this is where I've gotten stuck. The audio player appears accordingly, but you cannot play any audio. I've tried to check via Chromes DevTools and there the source, or src, is the correct file path to the files. <source src="audio_player/media/audio_player/Song.wav" type="audio/wav"> I've been going crazy for the last day or so trying to figure out what is causing it not to work. I spent a lot of time trying to get it to source the correct path for the files but even though it seems to do that … - 
        
Dockerize Nginx and Gunicorn or not?
I am running a django project bootstrapped with cookiecutter using docker and an AWS database. I am using Heroku for deployment. Now, since my app is getting bigger I want to change from Heroku to sth else and in the process change infrastructure. I would like to setup Nginx and Gunicorn since that seems to be the standard. Now my docker knowledge is limited, that's why my question is: Should I put Nginx into a docker container and Gunicorn as well? Or is it better to install Nginx/Gunicorn on DigitalOcean/AWS without docker? Or how would I go about that? Thanks in advance for hints and help! Greatly appreciated - 
        
Add more than one label in ModelChoiceField - Django
I have this kind of model: class Cities(models.Model): country = models.CharField(max_length=45, blank=True, null=True) city = models.CharField(max_length=45, blank=True, null=True) def get_city_name(self): if self.sub_species: return str(self.country) + " " + str(self.city) With this data by example in my model: France Paris France Lyon France Marseille Germany Berlin Germany Bonn views.py filter_drop_down_menu_city = CityNameForm() forms.py class CityNameChoiceField(forms.ModelChoiceField): """ CityNameChoiceField Class """ def label_from_instance(self, obj): """ This function return the label of the instance :param obj: :return: """ return obj.get_city_name() class CityNameForm(forms.Form): """ CityNameForm Class """ cityName = CityNameChoiceField( queryset=Cities.objects.order_by('country', 'city'), empty_label="(ALL Cities)", help_text="", required=False, label='Cities', ) In my template my choice field render the list of cities listed before. But i want that kind of choice render: France France Paris France Lyon France Marseille Germany Germany Berlin Germany Bonn The user can choice a country too (and after i can make the city selection) - 
        
Django two models with many-to-many relation print on template
I have category and product models. These have a many-to-many relation. My models class ProductCategories(models.Model): name = models.CharField(max_length = 60) image = models.ImageField(upload_to = 'ProductCategories') publish_date = models.DateTimeField(auto_now=False, auto_now_add=True) is_available = models.BooleanField() class Product(models.Model): category = models.ManyToManyField(ProductCategories) name = models.CharField(max_length = 60) price = models.DecimalField(max_digits=65, decimal_places=2) description = models.TextField() options = models.TextField() tags = models.TextField() publish_date = models.DateTimeField(auto_now=False, auto_now_add=True) stock_number = models.IntegerField() is_available = models.BooleanField() My view def category(request): categories = ProductCategories.objects.all() products = Product.objects.none() for category in categories: products = products.union(Product.objects.filter(category = category)[:4]) return render(request, 'shop/shopping.html', {'categories' : categories, 'products' : products}) My Html {% for category in categories %} <div class="row"> <h3 style="padding-left: 15px; padding-bottom: 15px">{% filter upper %}{{ category.name }}{% endfilter %}</h3> </div> <div class="row"> {% for product in products %} {{ product.category }} {% endfor %} </div> {% endfor %} I would like to list categories. Under each category, 4 products will be listed. is it possible to pass queryset which includes both products and their categories? Thanks, - 
        
Expected view ShowImageList to be called with a URL keyword argument named "pk"
I am getting below issue while accessing the urls /show_image/, /products/, /categories/. But show_image/(?P[\w-]+)/$ url is working fine Expected view ShowImageList to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly. My urls.py is url(r'^products',ProductList.as_view({'get': 'retrieve'}), name="product-list"), url(r'^show_image/$', ShowImageList.as_view({'get': 'retrieve'}), name='ShowImage'), url(r'^show_image/(?P<pk>[\w-]+)/$', ShowImageDetail.as_view({'get': 'retrieve'}), name='image_detail'), url(r'^categories/', Categories.as_view({'get': 'retrieve'}), name= 'categories'), - 
        
How to pass UserCreationForm inside another built-in view (like FormView)
As a beginner, I am trying to skim through the Django documentation. In order to allow a user to register, I want to create a register view. Now, I have seen many examples on how to do this with a function-based view which passes the built-in UserCreationForm. What I am trying to do is to take advantages of all the built-in views, so I was wondering if is possible to pass the UserCreationForm inside, let's say, the built-in FormView. At the moment I have managed to render the form at the required URL, but once submitted, it doesn't create the user even though it redirects me to the home page (as wanted). How can I fix this? Here is my views.py from django.shortcuts import render from django.contrib.auth.forms import UserCreationForm from django.views.generic.edit import FormView class RegisterView(FormView): template_name = 'registration/register.html' form_class = UserCreationForm success_url = '/home/' And here my html {% block content %} <form method="post" action="{% url 'home' %}"> {% csrf_token %} <table> <tr> <td>{{ form.username.label_tag }}</td> <td>{{ form.username }}</td> </tr> <tr> <td>{{ form.password1.label_tag }}</td> <td>{{ form.password1 }}</td> <td>{{ form.password2.label_tag }}</td> <td>{{ form.password2 }}</td> </tr> </table> <input type="submit" value="Register"> </form> {% endblock %} - 
        
Django return not loading all dependencies
So I created a login page in django and has various Java script css dependencies, which i have placed in the same folder and provided proper script locations. When I test only the page in browser it seems to load fine with all the files, however whenever i send any request and when django returns the web page using return render(request, 'InsertPage/login.html') Only the web page is returned and not the dependent files. - 
        
how to solve cannot read property 'mDATA' in Datatables
I have configured datatables with django, its working perfectly when having maximum of 6 column. When i tried to add one more column i'm getting error "Uncaught TypeError: Cannot read property 'mData' of undefined" When i inspect in chrome, get line (c.mData ===) where the error shows: if(c.mData=== a){var d=w(b,"sort")||w(b,"order"),e=w(b,"filter")||w(b,"search");if(d!==null||e!==null){c.mData={_:a+".display",sort:d!==null?a+".@data-"+d:k,type:d!==null?a+".@data-"+d:k,filter:e!==null?a+".@data-"+e:k};ja(p,a)}}})}var T=p.oFeatures,e=function(){if(g.aaSorting===k){var a=p.aaSorting;j=0;for(i=a.length;j I tried to give static data to check whether it because of dynamic render, still the same issue came. This is my html page, table.html <div class="row mb-4"> <div class="col-12 mb-4"> <div class="card"> <div class="card-body"> <table class="data-table data-table-feature" id="dtable"> <thead> <tr> <th>Code</th> <th>Description</th> <th>Sort key</th> <th>Is delete</th> <th>Prefix</th> <th>Edit</th> <th>TEST</th> </tr> </thead> <tbody> {% for i in areas %} <tr> <td>{{ i.code }}</td> <td>{{ i.description }}</td> <td>{{ i.sort_key }}</td> <td>{{ i.is_deleted }}</td> <td>{{ i.prefix }}</td> <td><a href="{% url 'edit-area-master' i.id %}">edit</a></td> <td>TEST</td> </tr> {% endfor %} </tbody> </table> </div> </div> </div> </div> I cross checked all table tags, please point out where i went wrong. - 
        
How to check the occurrence of a value in a m2m field in Django?
I want to display a list of icons that were "purchased" by the user, for this i try to check if the user is in icon.buyers, but I getting this error: TypeError: argument of type 'ManyRelatedManager' is not iterable in line: if request.user in icon.buyers:. Is there any other way to do this? models.py: class Icon(models.Model): ... buyers = models.ManyToManyField(User, blank=True) views.py: class MyIconsView(APIView): def get(self, request): my_icons =[] icons = Icon.objects.all() for icon in icons: if request.user in icon.buyers: my_icons += icon serializer = LicensedIconSerializer(my_icons, many=True) return Response({"my icons": serializer.data}) - 
        
Django signal to recognise which view called
I have a model with two different views. The problem is that I have a signal registered to the model, and I want to change the behaviour of the signal based on what view called the object save method. Is there a way doing so? - 
        
Psycopg2: to upgrade or not to upgrade
I've just upgraded my development virtual environment from Django 1.11 to the latest 2 release (2.2.8), and upgraded various well-known apps and django support also to the latest. All seems good after fixing various backward-incompatibilities. Now I'm reviewing pip list -o results, to see what hasn't been upgraded. Most are application codes that I can review myself. However, psycopg2 is an essential bit of "plumbing" between Django and Postgresql (which I've just upgraded to 12). I have 2.7.3.2 installed. The latest is 2.8.4. I don't have any feel for what upgrading it means or does or fixes, and what any problems might look like. Am I right to assume that upgrade-installing Django would have upgraded Psycopg2 if the Django version wasn't happy with what was already installed? Where do I find out what is recommended for this version of Django? And more generally, should I upgrade it anyway, and if so to the most recent 2.7 or the most recent 2.8? (FWIW I note Centos 7.7 is shipping a mere 2.5.1 !) - 
        
Unable to host multiple sites on same domain in django using Apache2.4
I am new to django and i was working on an application in which i need to host three different django projects on same domain name. I have tried all the ways that i get on internet.Please help me with the solution what and how i can do this.I am using Django 2.2 version on windows.Each project has its own virtual environment and each have different wsgi file. Let i am using a domain name - example.com and three projects project1,project2,project3 so i want to host them like- example.com/project1 - It wil refer to project1 example.com/project2 - It wil refer to project2 example.com/project3 - It wil refer to project3 I have kept these projects in htdocs of apache. httpd-vhosts.py Listen 80 <VirtualHost *:80> ServerName example.com WSGIScriptAlias / "C:/Apache24/htdocs/mainApp/project1/src/src/wsgi_windows.py" Alias /static "C:/Apache24/htdocs/mainApp/project1/Research/src/static" <Directory "C:/Apache24/htdocs/mainApp/project1/src/src/"> <Files wsgi_windows.py> AllowOverride none Require all granted </Files> </Directory> <Directory "C:/Apache24/htdocs/mainApp/project1/src/static"> AllowOverride none Require all granted </Directory> </VirtualHost> Same code i have written for project2 by replacing project1 to project2 but its working for project1 but not for project2 This is my configuration file to create virtual hosts - 
        
Rest Auth Set Login as Mobile Number
I am trying to add a new field mobile number in my custom user field and setting as the USERNAME_FIELD. I want to have this field inside the rest-auth but somehow I get a blank mobile number. The user is created but the mobile number field is always blank and get an exception of Foreign Key Constraint Failed because it tries to create a token and as the mobile number is None, hence the exception. from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) # Create your models here. class UserManager(BaseUserManager): def create_user(self, mobile_number, password=None): """ Creates and saves a User with the given email and password. """ if not mobile_number: raise ValueError('Users must have an mobile number') user = self.model( mobile_number = mobile_number, ) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, mobile_number, password): """ Creates and saves a staff user with the given email and password. """ user = self.create_user( mobile_number = mobile_number, password=password, ) user.staff = True user.save(using=self._db) return user def create_superuser(self, mobile_number, password): """ Creates and saves a superuser with the given email and password. """ user = self.create_user( mobile_number = mobile_number, password=password, ) user.staff = True user.admin = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', … - 
        
django.setup(); django.core.exceptions.ImproperlyConfigured:
The Error is django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. and my code is here import os import django # import pdb os.environ.setdefault('DJANGO_SETTING_MODULE', 'studentproject.settings') # pdb.set_trace() django.setup() from testapp.models import * from faker import Faker from random import * faker= Faker() def fakedata(n): for i in range(n): fsroll = randint(10000, 99999) fsname = faker.name() fsmarks =faker.random_int(min=1, max= 100) fdob =faker.date() fsemail=faker.email() fphn= randint(6000000000,9999999999) faddr = faker.city() student_record= students.objects.get_or_create(Roll_no = fsroll, Sname=fsname, Marks= fsmarks, DOB= fdob, Email= fsemail, Phn= fphn, Address= faddr) fakedata(100) I have tried this also In PyCharm -> Settings -> Build, Execution, Deployment -> Console -> Django Console there's a dedicated button to set Environment variables. Open it and add DJANGO_SETTINGS_MODULE = some_project.settings - 
        
how Adding query string to url in jquery in django template
Im trying to add query string to url using jquery and when i do it using browser console by type location.href = '?grouping_by='+ 'daily' + '&start_date=123123123123'; it works fine and the browser take it. but when im trying to add it in my html template it fails here my code <script> $("#submit").click(function () { $("#target").click(); var $grouping_by = $("#grouping_by"); var $start_date = $("#start_date"); var grouping_by = $grouping_by.val(); var str_start_date = $start_date.val(); var url = '?grouping_by=' + grouping_by + '&start_date=' + str_start_date; location.href = '?grouping_by='+ 'daily' + '&start_date=123123123123'; }); </script> I tried location.path and pathname but also nothing happens any help ?