Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to find nearest user in google map using map API In Django?
I have a list of delivery agents(bikers) for a restaurant in the MYSQL database with longitude and latitude(updating in every 10 seconds). I want if the restaurant gets a new order nearest agent will get the message. I am stuck over how to do in Django. I know geoDjango is useful but it will give liner distance between two points. Can someone help me to get the nearest person on the map? -
How to filter FK dropdown values in django admin
I want to display only Admin and and Manager Role in Dropdown list. here are my Models UserProfile and Roles. class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user_company = models.ForeignKey(Company, on_delete=models.CASCADE) user_role = models.ForeignKey(Roles, on_delete=models.CASCADE) class Roles(models.Model): role_title = models.CharField(max_length=30) role_description = models.CharField(max_length=100) -
Delete user directly from html template
I want to create a management page where an admin can delete users. I have succesfully made it list created users, but now i'm struggeling with how to create a deleteView to delete the user entirely from my django project. Views.py def index(request): users = User.objects.all() return render(request, 'EditUser.html',{'userlist':users}) def deletefunction(request,User =None): object = User.objects.get(id=User) object.delete() return render(request,'EditUser.html') Project urls.py from edit_user.views import deletefunction urlpatterns = [ path('admin/', admin.site.urls), path('management', include('management.urls')), path('management/create', include('signup.urls')), path('management/edit', include('edit_user.urls')), path('^delete/(?P<User>[0-9]+)/$', deletefunction, name='delete_view'), ] HTML code <div class="container"> {% for item in userlist %} <tr> <td>{{ item.username }}</td><a href="{% url 'EditUser:deletefunction' User %}">delete</a> </tr> {% endfor %} </div> As of right now when i'm trying to load my page i'm receiving this exception. Reverse for 'deletefunction' not found. 'deletefunction' is not a valid view function or pattern name. -
Django: get full URL with reverse
If I print after_auth_url from the below view, it will be only "/collect/". How do I make it a full URL, like "whatever_comes_before_the_particular_page_name/collect/", so I can put it in auth_url string? def authorize(request): after_auth_url = reverse('explorer:collect') auth_url = 'https://www.strava.com/oauth/authorize?client_id=9999&response_type=code&redirect_uri={url}&approval_prompt=force'.format(url=after_auth_url) return redirect(auth_url) -
Django - Access changed InlineAdmin fields within parent Admin's save_model()
Apologize if this question has already been addressed before. Since I was not able to find a proper solution for this, had to ask. I need to perform an action(an API call telling my clients to update models from their end) when there is a change in a model's Inline Admin fields from within the save_model() of the parent admin. models.py class Student(models.Model) name = CharField() age = DateField() class Marks(models.Model) student = ForeignKey(Student) subject = CharField() marks = IntegerField() admin.py class MarksInline(admin.TabularInline): model = Marks form = MarksForm formset = MarksInlineFormSet class StudentAdmin(admin.ModelAdmin): form = StudentForm inlines = [MarksInline, ] I am able to achieve this by checking the form.changed_data from within the StudentAdmin save_model() and for the MarksInline models MarksInlineFormSet clean() method. The issue is my action will be called separately from each of these methods resulting in two calls, even though all I need is a single call to update the Student and Marks model in the clients end. My problem would be solved if the save_model() of StudentAdmin could return the fields that has been changed via form.changed_data in MarksInline as well. Tried to use post_save signals as well by implementing Field Tracker. But this too … -
Using Email as login in Django
I am not able to login in django with correct password and email. here is my code. backends.py from django.contrib.auth.models import User class Emailbackend(object): def authenticate(self, username=None, password=None, **kwargs): try: user = User.objects.get(email=username) except User.MultipleObjectsReturned: user = User.objects.filter(email=username).order_by('id').first() except User.DoesNotExist: return None if getattr(user, 'is_active') and user.check_password(password): return user return None def get_user(self, user_id): try: User.objects.get(pk=user_id) except User.DoesNotExist: return None Settings.py AUTHENTICATION_BACKENDS = ( 'users.backends.Emailbackend', ) -
django postgres password authentication failed
I am trying to connect Django with postgres but i am getting this error `File "/home/tbosss/Desktop/environment/test_api/venv/lib/python3.6/site-packages/psycopg2/init.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: FATAL: password authentication failed for user "tbosss" FATAL: password authentication failed for user "tbosss" this is my setting.py: 'default' : { 'ENGINE' : 'django.db.backends.postgresql_psycopg2', 'NAME' : 'login', 'USERNAME' : 'postgres', 'PASSWORD' :'123', 'HOST' : 'localhost', 'PORT' : '5432' } tbosss is the root its should be postgre user. its not connecting to postgre. here the list of database from terminal List of databases Name | Owner | Encoding | Collate | Ctype | Access privileges -----------+----------+----------+-------------+-------------+----------------------- login | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =Tc/postgres + | | | | | postgres=CTc/postgres+ | | | | | admin=CTc/postgres postgres | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | template0 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/postgres + | | | | | postgres=CTc/postgres template1 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/postgres + | | | | | postgres=CTc/postgres -
Adding row to another table before inserting a row
I have a tag model like this: class Tag(models.Model): tag = models.CharField(max_length=100) and an image model like this: class Image(models.Model): image_name=models.CharField(max_length=40,unique=False) ... tags = models.ManyToManyField(Tag) It is currently taking the primary key of the tags table in the array instead of the string values like this: { "image_name" : "abc.png", "tags" : [1, 2] } However, I want to be able to create a new image with POST request with multiple tags, something like this: { "image_name" : "abc.png", "tags" : ["logo", "abc"] } When I do this, I want logo and abc to be inserted into Tags table automatically. Is ManyToManyField correct way to do this? If so, how to achieve this? -
I would like to know how to retrieve and display data in the database with a select menu?
I would like to display a data in an input tag with a select menu /home/bruel/Téléchargements/Capture du 2018-12-26 14-00-44.png /home/bruel/Téléchargements/Capture du 2018-12-26 14-02-27.png -
Django KeyError 'pk' POST method
i have post method in form for sort objects <form method="post" action="{% url 'package_dashboard' %}"> {% csrf_token %} <button type="submit" name="order_by_title">sortByName</button> <button type="submit" name="order_by_date">sortByDate</button> </form> my views.py class PackageDashboardView(PackageAccessMixin, ListView): model = Package template_name = "packages/dashboard.html" def get_queryset(self): queryset = Package.objects.all().order_by('title', 'version__name'). \ select_related('title', 'version').defer('title__metadata', 'validation', 'translations', 'diff_fields') if "order_by_date" in self.request.GET: queryset = Package.objects.all().order_by('-started', 'version__name'). \ select_related('title', 'version').defer('title__metadata', 'validation', 'translations', 'diff_fields') elif 'order_by_title' in self.request.GET: queryset = Package.objects.all().order_by('title', 'version__name'). \ select_related('title', 'version').defer('title__metadata', 'validation', 'translations', 'diff_fields') return queryset my urls.py url(r'^packages/$', packages.PackageDashboardView.as_view(), name="package_dashboard"), the error Internal Server Error: /packages/ Traceback (most recent call last): File "/home/abdel/Desktop/eclair-packager/eclair_env/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/abdel/Desktop/eclair-packager/eclair_env/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/abdel/Desktop/eclair-packager/eclair_env/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/abdel/Desktop/eclair-packager/eclair_env/lib/python3.6/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/home/abdel/Desktop/eclair-packager/packager/permission_mixins.py", line 20, in dispatch return super().dispatch(request, *args, **kwargs) File "/home/abdel/Desktop/eclair-packager/eclair_env/lib/python3.6/site-packages/django/contrib/auth/mixins.py", line 56, in dispatch return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs) File "/home/abdel/Desktop/eclair-packager/eclair_env/lib/python3.6/site-packages/django/views/generic/base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "/home/abdel/Desktop/eclair-packager/packager/permission_mixins.py", line 96, in post obj = self.get_package() File "/home/abdel/Desktop/eclair-packager/packager/permission_mixins.py", line 78, in get_package return get_object_or_404(Package, pk=self.kwargs['pk'], **kwargs) KeyError: 'pk' [26/Dec/2018 11:35:56] "POST /packages/ HTTP/1.1" 500 109583 -
Django update database on network messages
I am fairly new to Django and friends. I want to build a web app that listens to qpid and displays some info in a browser. For example I want it to listen to heartbeats of other applications, and show the status in the browser. My first attempt is to have a model that just stores data for apps class Apps(models.Model): last_hb = models.DateTimeField() .... And display those apps in a table using django_tables2. How can I run a process from within django that would be able to listen to qpid and update the App database model continuously? -
custom styling of django formset using bootstrap
the template contains a formset having 9 fields .we want to style it using bootstrap by diividing the formset into 3 rows each where each row contains only 3 fields template.html <table class="table"> {{ contactperson_form.management_form }} {% for form in contactperson_form.forms %} {% if forloop.first %} <thead> <tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr> </thead> {% endif %} {% for field in form.visible_fields %} <tr class="{% cycle row1 row2 %} formset_row"> <td> {# Include the hidden fields in the form #} {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endif %} {{ field.errors.as_ul }} {{ field }} </td> {% endfor %} </tr> {% endfor %} -
can we define database name in models.py in django?
I have multiple databases defined in settings.py.In models.py I have to use auth_user table from defined datbase rather from the default database.How can we define that in models.py? I have databases defined in settings.py as below: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'sources', 'USER': 'root', 'PASSWORD': 'cdffd@123', 'HOST': 'xx.xx.xx.xxx', 'PORT': '3306', }, 'abc': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'customers', 'USER': 'root', 'PASSWORD': 'dsgfsd@123', 'HOST': 'xx.xx.xx.xxx', 'PORT': '3306', }, 'xyz': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'users', 'USER': 'root', 'PASSWORD': 'ewet@123', 'HOST': 'xx.xx.xx.xxx', 'PORT': '3306', }, } in my models.py i have defined user model as below: class User(AbstractBaseUser, PermissionsMixin, BaseUserManager): name_regex = RegexValidator(regex="^[a-zA-Z]+$",message="Enter only Alphabets")#regular expression for name email_regex = RegexValidator(regex="^\w.+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$",message="Enter valid Email Id")#regular expression for email password = models.CharField(_("Password"),max_length=128,default='') last_login = models.DateTimeField(_('date Last Login'), null=True, blank=True) is_superuser = models.BooleanField(_("Super User"),default=0) username = models.CharField(_('Username'), max_length=75,blank=True,null=True) first_name = models.CharField(_('First name'),default='',blank=True,null=True, max_length=20) last_name = models.CharField(_('Last name'),default='',blank=True,null=True, max_length=20) email = models.EmailField(_('Enter your email address'),unique=True,max_length=254,error_messages={'unique':"Email ID already registered.",'invalid':'Enter valid Email ID'}) is_staff = models.BooleanField(_('staff status'), default=False) is_active = models.BooleanField(_('active'), default=True)#A boolean attribute that indicates whether the user is considered “active” date_joined = models.DateTimeField(_('Date joined')) iRoleID = models.IntegerField(_("Role"),default=0) iModifiedBy = models.IntegerField(_("Modified By"),blank=True,null=True) dtModifiedOn = models.DateTimeField(_("Modified On"),blank=True,null=True) apitoken_validity = models.IntegerField(default=0) authentication_type = models.IntegerField(default=1) iMSISDN = models.IntegerField(_('Mobile Number'),default=0) … -
how to add paypal to your project with default rest_framework settings witout using template and forms
i want to integrate paypal in my project ...how should i add and what n all i need .....like changes in models.py,views.py,serializers.py,url.py -
How to handle two forms in a html template
I have two models workorders(w_orders) and objects(tobjects). I have created two templates workorder_create and workorder_edit. workorder_create should contain some data of the w_orders model meanwhile workorder_edit should contain all the data for both models w_orders and tobjects. workorder_create works meanwhile workorder_edit doesn't. This is my code: models.py class w_orders(models.Model): Id = models.BigAutoField(primary_key=True) datedefwo = models.DateField(default=datetime.now) datesched = models.DateField(blank=True, null=True) datefinished = models.DateField(blank=True, null=True) sign = models.BigIntegerField(blank=True, null=True) statusid = models.BigIntegerField(blank=True, null=True, default=1, choices=STATUS_CHOICES) typeid = models.BigIntegerField(blank=True, null=True, default=1, choices=TYPE_CHOICES) comments = models.CharField(max_length=254, blank=True, null=True) navid = models.BigIntegerField(blank=True, null=True) navkonsid = models.CharField(max_length=12, blank=True, null=True) navname = models.CharField(max_length=254, blank=True, null=True) navcustadr = models.CharField(max_length=254, blank=True, null=True) navdebt = models.FloatField(blank=True, null=True) navpropcode = models.CharField(max_length=254, blank=True, null=True) navdepcode = models.CharField(max_length=254, blank=True, null=True) navphoneno = models.CharField(max_length=254, blank=True, null=True) navreasoncomp = models.CharField(max_length=254, blank=True, null=True) nightshift = models.BooleanField(default=False) priority = models.BigIntegerField(blank=True, null=True) stid = models.BigIntegerField(blank=True, null=True) mapurl = models.CharField(max_length=254, blank=True, null=True) def __unicode__(self): return self.Id class tobjects(models.Model): oid = models.BigAutoField(primary_key=True) wid = models.ForeignKey(w_orders, on_delete=models.CASCADE) objtypegisid = models.BigIntegerField(blank=True, null=True, default=1) objgisid = models.BigIntegerField(blank=True, null=True, default=1) condgenid = models.BigIntegerField(blank=True, null=True, default=1) condriskid = models.BigIntegerField(blank=True, null=True, default=1) condratsid = models.BigIntegerField(blank=True, null=True, default=1) condmhcoverid = models.BigIntegerField(blank=True, null=True, default=1) condmhwallid = models.BigIntegerField(blank=True, null=True, default=1) condpipehydrsid = models.BigIntegerField(blank=True, null=True, default=1) condpipehydreid = models.BigIntegerField(blank=True, null=True, … -
How to have specific related names for proxy models
Consider the models below: class Engine(models.Model): Name = models.CharField(max_length=50, unique=True) class Port(models.Model): Model_generic = models.ForeignKey(Engine, on_delete=models.CASCADE, related_name='Ports') Name = models.CharField(max_length=150) Type_IO = models.BooleanField(choices=((True, 'IN'), (False,'OUT'))) class Port_IO_Manager(models.Manager): def __init__(self, inout): super().__init__() self.inout = inout def get_queryset(self): return super().get_queryset().filter(Type_IO=self.inout) class Port_IN(Port): objects = Port_IO_Manager(True) class Meta(Port.Meta): proxy = True class Port_OUT(Port): objects = Port_IO_Manager(False) class Meta(Port.Meta): proxy = True How can I define related names Ports_IN and Ports_OUT so I can use things like: Engine.objects.filter(Ports_IN__Name__contains='TR') -
How to return XML to ajax in django?
I want to return XML data back to the client that can be displayed as a graph in mxGraph. My main goal is to save the mxGraph to the server, so whenever a user accesses the same page, the graph displayed is the same graph where the user left it. The xml data is getting saved in the server but is not getting returned as an xml back to the client. Currently, I tried to return it as JSON, thinking it would be okay to use the value as XML. However, there are "/n" being returned with it, so it doesn't parse properly. views.py def saveData(request, user): if request.method == "POST": #Get user profile member = Member.objects.get(username=user) #Get XML data once user presses save #xmlData = request.POST['xml'] member.data = request.POST['xml'] member.save() print(member.data) response = JsonResponse([ member.data ], safe = False); #return render(request, 'fastcookapp/index.html', {"xmlData": member.data}) return HttpResponse(response, content_type="application/json") return HttpResponse('POST is not used') ajax var button = mxUtils.button('Save', function() { var encoder = new mxCodec(); var node = encoder.encode(graph.getModel()); var xml = mxUtils.getPrettyXml(node); var csrftoken = getCookie('csrftoken'); $.ajax({ type: "POST", url: "/saveData/", data: { "xml": xml}, headers:{ "X-CSRFToken": csrftoken }, success: function(data){ console.log("data" + data[0]) //functions in mxgraph to decode … -
how to remove port 8000 from the webpages URL http://dev.myapplication.io:8000. I wanna my url like be http://dev.myapplication.io
i build a website by using django, reactjs,aws. And I want to remove port 8000 from the url. http://dev.myapplication.io:8000 -
How to use results of annotated subquery in DJango
I have following model: class CollegeResult(models.Model): id = models.IntegerField(primary_key=True) college_code = models.CharField(max_length=255, blank=True, null=True) college_name = models.CharField(max_length=255, blank=True, null=True) branch_name = models.CharField(max_length=255, blank=True, null=True) cutoff_type = models.CharField(max_length=255, blank=True, null=True) stage_mark = models.IntegerField(blank=True, null=True) stage_rank = models.IntegerField(blank=True, null=True) I want to list rows with max(stage_mark) from group of college_code,branch_name. Approaches I tried: Raw query, but it is vulnerable to SQL Injection. query1 = CollegeResult.objects.filter(cutoff_type__in=quota) query2 = query1.values('college_code', 'branch_name').annotate(stage_mark=Max('stage_mark'))But I don't know how to use query2 results to filter query1 result. query1 = CollegeResult.objects.filter(cutoff_type__in=quota) query2 = query1.values('college_code', 'branch_name').annotate(stage_mark=Max('stage_mark')) q_statement = Q() for college in query2: q_statement |= (Q(college_code=college['college_code']) & Q(branch_name=college['branch_name']) & Q( stage_mark=college['stage_mark'])) query3 = query1.filter(q_statement) This is giving django.db.utils.OperationalError: too many SQL variables How I should approach ? -
Can anyone explain me how to open a python script file which is written using selenium and by taking input from Django custom form?
Can anyone explain me how to open a python script file which is written using selenium and by taking input from Django custom form? I have included small script below here is the code - script.py: from selenium import webdriver # To activate the webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.keys import Keys # keys to send import time # For using sleep() chrome_options = Options() chrome_options.add_argument('--start-maximized') # for Chrome Maximized size # Disabling 'Chrome is being controlled by automated test software' popup on chrome chrome_options.add_argument("--disable-infobars") # browser = webdriver.Chrome('./chromedriver',chrome_options=chrome_options) browser = webdriver.Chrome('C:\\Users\\anilg\\Desktop\\python\\chrome-webdriver\\chromedriver.exe', chrome_options=chrome_options) browser.get("https://www.youtube.com/") time.sleep(1) search_field1 = browser.find_element_by_id('search') search_field1.send_keys('python django') time.sleep(1) search_btn1 = browser.find_element_by_css_selector("#search-icon-legacy").send_keys(Keys.ENTER) time.sleep(10) browser.close() Here the input is “python django” which I have manually entered in the script.py file but this value should come from Django custom form by input field once we submit the form then the value should be redirected to script.py and then the script.py file should run and should execute the script. Can anyone explain this process using your Django custom form class on youtube or share me on stackoverflow using code? Thanks for your help in advance. Anil. -
Deployong Django App to Heroku but Heroku pip install can't find module versions matching the requirement.txt
So, I have been trying to deploy my Django app to heroku, but Heroku is trying to pip install older versions of the module that are listed in the requirements.txt i.e. Heroku is trying to install anaconda-client==1.2.2 but we got anaconda-client==1.7.2 when we do a pip install locally. -
How to subtract two date and get the number of days in annotate?
I'm making a query to get the number of days from the date that a person bought a new phone until today. device_record = Devc.objects.annotate(duration = todays_date - F('datebuy'))\ .order_by('datebuy') When I retrieve the data, i got this 3150 days, 20:08:00 . How can I do to remove the time because I just want to display the number of days? -
Is there a way that we can avoid multiple token generations for a single user if he/she try to login on different browsers?
I am using django-rest-framework-jwt in my backend and calling API's from Angular Project. When user try to login on multiple Browsers, each time a new token is generated for the user on new browser. And every token is valid. What I want is that when user is already logged in in one browser and he/she tries to login on second different browser the previous token for first browser should be invalidated. -
CSRF errors when trying to add simple product to shopping cart
I am getting the error CSRF verification failed. Request aborted. when trying to use 'add to cart' with a simple cart application I wrote. The code in my template: <form action="{% url "cart:cart_add" instance.id %}" method="post"> {% csrf_token %} {{ cart_product_form }} <input type="submit" value="add to cart"> </form> And my views from views.py: @require_POST def cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update']) return redirect('cart:cart_detail') def cart_detail(request): template = loader.get_template('/webapps/my_webapp/furniture_site/cart/templates/cart/detail.html') cart = Cart(request) for item in cart: item['update_quantity_form'] = CartAddProductForm(initial={'quantity': item['quantity'], 'update': True}) context={'cart': cart} return HttpResponse(template.render(context)) Everything seems fine as far as I can see, what am I missing? -
TypeError: 'AnonymousUser' object is not iterable
def gmail_authenticate(request): storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential') credential = storage.get() if credential is None or credential.invalid: FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user) authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url) else: http = httplib2.Http() http = credential.authorize(http) service = build('gmail', 'v1', http = http) print('access_token = ', credential.access_token) status = True return render(request, 'index.html', {'status': status}) i'm getting TypeError: 'AnonymousUser' object is not iterable while reading the credentials i'm getting below error. File "C:\Users\admin\Desktop\GmailTest\google- login\gfglogin\gfgauth\views.py", line 10, in gmail_authenticate credential = storage.get() TypeError: 'AnonymousUser' object is not iterable [26/Dec/2018 12:51:07] "GET /auth/ HTTP/1.1" 500 111109 i'm expecting to authenticate the gmail user.