Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Selenium Django-Python with Chrome, I can't find the element with xpath - NoSuchElementException for form
I ran selenium webdriver on django and it throws this error. I have tried both the usual xpath method and EC method. I get the same error. What should I do? Here is the url for this: https://login.fmls.com/SAML/login.aspx?ReturnUrl=%2fsaml%2fSAML%2fSSOService.aspx%3fSAMLRequest%3djZLNTsMwEIRfJfKBWxLHrWhrmqCKCilSEagBDlyQ62waS7EdvE7VxydJy98BxMXyrnY934y8RKGblq86X5stvHWAPsjXKXlNaLUDyapwBxULp7tJFQo6KcOFhHkypwDsckaCZ3CorEkJiygJcsQOcoNeGN%252B3aLII6TRk88ck4RPK2Sxi08ULCda9ijLCj5u19y3yOG7sXpmo0g1G0up44IqL1d0mLor7AtxBSYgEtkcS3FonYSROSSUahEH5QSCqA3x2VojgBoUba7DT4M5v5KaEY0ro7xNP280XlRbeqeOIVUb9ca4HwtP1zD2QXbc9g6%252Bd7fZ1yi6Ebq%252BMdVAqB9KnCQmOujHIx8RT0jnDrUCF3AgNyL3kg13eJ8lbZ72VtiHZcpjmY7Du2%252F7f6%252BLDGcn%252B7WMZf1PKTtXPf5G9Aw%253D%253D%26RelayState%3dMatrix%2bSAML%2bLogin from selenium import webdriver from selenium.webdriver.support.ui import Select from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By def login_mls(self): self.driver.get(self.info["url"]) form = self.driver.find_element_by_xpath("//form") # form = WebDriverWait(self.driver, 4).until(EC.presence_of_element_located((By.XPATH, "//form"))) -
(Django) Showing simple stats about model instances
What would be the correct approach to create a "stats block" which could be used easily? I've now created a simple page template and view function which returns a list of stats e.g. users and user count by calling User.objects.all().count() How should this be implemented to be able to include these stats in any template? And perhaps with different styles such as list, inline, bootstrap panel etc? -
How to fix issues with Django registration template importation/referencing
I have recently started a blog using django from Corey Schaeffer's tutorial. I am stuck at part 6: User Registration, the feedback says template does not exist at users/register.html at line 19. I have attempted to send the directory in settings to the absolute location of my templates, but it keeps responding with the same feedback. I must be incorrectly referencing in my register.html or settings. Or even worse, a clerical/technical error! My settings file import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'lzjtwkmz)f5nmj+@^vmiu^2rk+!24f1if72aq81+ny=wiiwn+g' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'users.apps.UsersConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'django_project2.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['C:/Users/sabay/django_project2/blog/templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'django_project2.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } my register.html file {% extends "blog/base.html" %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Join Today</legend> </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Sign Up</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> Already Have An Account? <a … -
How to serve Django and ASP.NET on same host in IIS?
I have a web application built in ASP.Net and deployed on IIS 8. I need to integrate a django project with this application. Is it possible to do it? And if yes, how? -
Retrieving FCM token in JavaScript
I'm trying to build a chat system using django for backend and FCM for notifications. Till now, I've been trying to retrieve FCM token, but I haven't been able to using the code below. When I try it, an alert pops up saying "Error retrieving token". What am I missing? I'm totally new to Firebase so I don't know really well how to deal with it. <script src="https://www.gstatic.com/firebasejs/5.10.0/firebase.js"></script> <!-- Firebase App is always required and must be first --> <script src="https://www.gstatic.com/firebasejs/5.8.4/firebase-app.js"></script> <!-- Add additional services that you want to use --> <script src="https://www.gstatic.com/firebasejs/5.8.4/firebase-auth.js"></script> <script src="https://www.gstatic.com/firebasejs/5.9.1/firebase-messaging.js"></script> <script> // Initialize Firebase var config = { apiKey: "", authDomain: "", databaseURL: "", projectId: "", storageBucket: "", messagingSenderId: "" }; firebase.initializeApp(config); </script> <script> function googleLogin(){ var provider = new firebase.auth.GoogleAuthProvider(); firebase.auth().useDeviceLanguage(); firebase.auth().signInWithPopup(provider).then(function(result) { // This gives you a Google Access Token. You can use it to access the Google API. var token = result.credential.accessToken; // The signed-in user info. var user = result.user; // ... firebase.auth().currentUser.getIdToken(/* forceRefresh */ true).then(function(idToken) { var csrftoken = '{{ csrf_token }}'; const messaging = firebase.messaging(); messaging.usePublicVapidKey(""); messaging.requestPermission().then(function() { console.log('Notification permission granted.'); messaging.getToken().then(function(currentToken) { if (currentToken) { alert(currentToken); $.post("/api/login", {'csrfmiddlewaretoken': csrftoken, 'token': idToken}); setTimeout(function(){ document.location.reload(true); }, 1500); } else { … -
Django: How to make a manager in the Django
I am new to django and working on a project where i want to make manager and admin. I have made the admin i.e. superuser but i have no idea how can i make a manager. I have tried to make a manager but it doesn't work for me. here is my views.py from where the manager is being detected. def login(request): if request.method =='POST': # print(request.POST) username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) print (user.has_perm('app.edit_task')) # return redirect('index') if user.is_superuser: return redirect('master') # elif user.has_perm('app.edit_task'): # return redirect('manager') elif user.is_staff: return redirect('manager') else: return redirect('index') else: messages.error(request, 'Invalid Credentials') return redirect('login') else: return render(request, 'vadash/sign-in.html') here is my models.py class manager(models.Model): name = models.CharField(max_length= 500) designation = models.CharField(max_length= 500) class Meta: permissions = [ ("edit_task", "can edit the task"), ] def __str__(self): return self.name class Create_Team(models.Model): first_name = models.CharField(max_length= 50) last_name = models.CharField(max_length= 50) company_name = models.CharField(max_length= 100) address = models.CharField(max_length= 1000) state = models.CharField(max_length= 100) status = models.CharField(max_length= 30) managers = models.ForeignKey('manager', on_delete = models.SET_NULL, null=True) I want to known that how can i make a manager and when ever a manager will be made then it will … -
Executing tasks with celery at periodic schedule
I am trying to execute a task with celery in Django.I want to execute the task at 12:30 pm everyday for which I have written this in my tasks.py @periodic_task(run_every=crontab(minute=30, hour=12), name="elast") def elast(): do something This is not working but if I want to schedule it at every 30 seconds I write this code @periodic_task(run_every=(timedelta(seconds=30)), name="elast") def elast(): do something This works.I wanted to know that what is wrong with the first piece of code?Any help would be appreciated. -
Why order invalid in django rawquery?
I run a raw sql query in django, order part are like: query_sql = """... ORDER BY %s %s""" ret = MyModel.objects.raw(query_sql, [order_field, order]) # print(ret.query) # ORDER BY cpc asc This is the generated order sql part The order is effective in mysql db , but always failed in my django raw query. What did I missed? How can I correct it? -
Design Question: Low load data aggregation for overview page
What is the best way to achieve low load on the database or application server for this use case: Let's say I want to build a web application that has for each user an overview page. The overview page shows in an aggregated form for each user the user's data. For example, if it were a library application it would show how many times the user visited the library in total, how many books he read in total, how many books were delivered delayed in total, how many minutes he spend in the building. Each time the user visits the overview page the up-to-date values should be displayed. While the user interacts with the site the numbers change. What I could do is for every overview page refresh do several counts in the database. But that would be expensive. I have thought I could store a JSON object with the data to be presented on the overview page in a database table and I update the JSON each time an event happend on the site which affects the count of objects. Or I could use a materiliazed view but to refresh it I would have to recalculate all the data … -
Unable to install mysqlclient for mac on mojave
I am using Python + Django + MySql in my web application. Whenever I tried to install mysqlclient I getting mutliple errors. Now I am stuck on this: when I ran pip install mysqlclient I am getting following error: Error Text Logs : https://pastebin.com/VrTGgpnr -
How to fix mysql django connection on mac OS?. I already installed mysqlclient but "Did you install mysqlclient?" Error displayed
I am setting a new Django 2.2 project with MySQL 8.0 on mac. I already installed mysqlclient and mysql-connector-python. When I hit python manage.py makemigrations this displayed "django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient?". I am using python 3.7. How can I solve this problem? I already installed pip install mysqlclient mysql-connector-python will not work for pyhton 3.7 import pymysql pymysql.install_as_MySQLdb() -
How create an online editor for python
I am going to build an online editor come compiler for python. I have some doubts. So, please give me some code links. -
How to update a M2M field in the related model upon form submission in django
I have a form that schedules a trip, in that form the user can select many vans. Once the user selects their vans, schedules the trip and submits the form, the van should then be marked unavailable in the database. How do I do this properly? I am aware that you can't use .update() on M2M fields. To get around this I tried to get the current form instance, and then from there run .update() on each individual van item that the user selects, but I had trouble getting it set up correctly. I am still new to Django so I am still learning how to deal with these minor tasks. I didn't want to try the .all() query set for fear of changing the availability status of all the vans in the related table. Here is part of the trip builder view: def post(self, request): """Take in user data, clean it, and then post it to the database.""" form = self.form_class(request.POST) # pass in the user's data to that was submitted in form if form.is_valid(): trip = form.save(commit=False) # create an object so we can clean the data before saving it # now get the clean and normalize the … -
How to get celery results model (using django-celery-results) within task
I'm planning on using django-celery-results backend to track status and results of Celery tasks. Is the django-celery-results backend suitable to store status of task while it is running, or only after it has finished? It's not clear when the TaskResult model is first created (upon task creation, task execution, or completion?) If it's created upon task creation, will the model status automatically be updated to RUNNING when the task is picked up, if task_track_started option is set? Can the TaskResult instance be accessed within the task function? Another question here appears to indicate so but doesnt mention task status update to RUNNING Thanks for any help -
Django file uploading and downloaing error
We use Django to build a front-end website to provide file processing, but if there are many people (more than 2 people) uploading files or downloading files, it will cause system errors. There are many reasons for errors, usually No such file, ...etc. There is a problem with requst and resbonse. Is there any solution? -
How to implement multiple login methods(types) with django authentication
I've used the django authentication before but only with one type of login, using username and password. How do i do the same thing if i need to have one method as username, password based and another using a unique id for login? -
How to upload photos by ajax in django?
Currently I'm trying to build a function that users can change their profiles, including email, names and photos. However, I have succeeded in changing email and names but I failed to change photos. My initial idea is that firstly I get the photo path and then pass the path to view.py. My html code is like: <input type="file" id="ava_up" name="ava_up" accept="image/png, image/jpeg, image/gif, image/jpg" /> My ajax code is: $(document).on('submit', '#profile_edit', function (e) { e.preventDefault(); var usr_nickname = $('#e_nickname').val(); var pattern = "%"; var res = usr_nickname.match(pattern) if(res){ $('#error_info').html("<b>Your nickname should not contain %.</b>") return; } var usr_email = $('#e_email').val(); var usr_photo = $('#ava_up').val(); $.ajax({ type:'POST', url:'./', data:{ async: false, avatar:usr_photo, nickname:usr_nickname, email:usr_email, csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success:function (response) { var t = $.parseJSON(response) if (t.code == 1){ $('#error_info').html("<b></b>") $('#done').modal('show') } else if (t.code == -2){ $('#error_info').html(t.message) } else { $('#error_info_2').html(t.message) } //window.location.reload() }, }) }) my View.py is: def edit_usr_profile(request): result = collections.OrderedDict() result['code'] = "" result['message'] = "" user = request.user objs = UserProfile.objects.filter(usr=user) usr_objs = UserProfile.objects.get(usr=user) if request.method == 'POST': if request.is_ajax(): try: usr_objs.avatar = request.FILES.get('avatar') usr_objs.nickname = request.POST.get('nickname') usr_objs.email = request.POST.get('email') usr_objs.save() result['code'] = "1" result['message'] = "" except Exception as e: if str(e) == "'avatar'": result['code'] = … -
django switching language takes to home page rather keep me in the same page
in my site i have language switch option [English , Spanish ]. suppose i am in about page now when i am switching language to English to Spanish its take me to home page . but i need to be in about page with new change language . As i am new in django i am little bit out of idea . any help would be really appreciable . <li> <a class="flag" href="[ ----- i want to make this href dynamic accoroding to current page url --------]"> <img src="{% static 'img/spa.png' %}" alt="en" width="25" height="25"> </a> </li> if its in about page in English language the url will be 'sp/about' or if its in Spanish language the url wil be 'en/about' -
Django -Instance a relationship model to a specific form
I got a problem when i want to instance my model to a form, Its a relationship model(One to one) Field, But it cant be instanced well, it just fetch objects of User model but not fetching a relationship model objects, Please help me... There is my code, but its not work!!! def update(request, id): test = User.objects.select_related('profile').prefetch_related('groups').get(id=id) if request.method == 'POST': form = UsersForm(request.POST or None, instance=test) form2 = UpdateAccountDetailForm(request.POST or None, instance=test) else: form = UsersForm(request.POST or None, instance=test) form2 = UpdateAccountDetailForm(request.POST or None, instance=test) return save_all(request, form, form2, 'projectuser/update.html') -
Django Rendering html from both Static directory and Tempalate Directory
I am building an AngularJS and Django Applicatoin. I have put my all static/AngularJS file in project/apps/static directory, also i have put html template that connected with angularJS in project/apps/static directory. Only i have put index.html in project/apps/template directory and it is rendering fine. You may ask me to put those html file of static file to put in project/apps/templates directory but if i put those html file in there, the angularJS will not find my templateURL so now i want to render html file from project/apps/static/test.html, is it possible? or let me know any possible solution for this Thanks for your time -
Using list serializer gives me an error 'list' object has no attribute 'filter'
I try to use ListSerializer for the purpose of filtering nested serializer. This works totally fine apart from one case while creating a new instance. The view.py is shown below: class NewGrade(generics.RetrieveUpdateDestroyAPIView): queryset = Grade.objects.all() serializer_class = NewGradeSerializer lookup_field = 'grade' def put(self, request, *args, **kwargs): try: flag = 1 s1 = kwargs["schoolName"] g1 = kwargs["grade"] Grade = Grade.objects.get(school__schoolName=s1, grade=g1) context = {'schoolName': kwargs["schoolName"]} serializer = NewGradeSerializer(Grade, context = context, data=request.data) except Grade.DoesNotExist: flag = 0 context = {'schoolName': kwargs["schoolName"]} serializer = NewGradeSerializer(context = context, data=request.data) if serializer.is_valid(): if flag == 0: serializer.create(validated_data=request.data) else: serializer.update(Grade,validated_data=request.data) else: return Response(serializer.errors) return Response(serializer.data, status=status.HTTP_200_OK) The nested serializer and the ListSerilazer is shown below: class FilteredData(serializers.ListSerializer): def to_representation(self, data): school = self.context.get("schoolName") data = data.filter(schoolID__schoolName=school) return super(FilteredData, self).to_representation(data) class StudentTemp(serializers.ModelSerializer): studentInfo = DisplayData(source="*") class Meta: model = Student list_serializer_class = FilteredData fields = ('studentInfo',) class DisplayData(serializers.Serializer): name = serializers.CharField() rollNum = serializers.CharField() class NewGradeSerializer(serializers.ModelSerializer): studentList = StudentTemp(many=True) class Meta: model = Grade fields = ("grade", "studentList") def create(self, validated_data): s1 = self.context.get("schoolName") sch = School.objects.get(schoolName=s1) student_datas = validated_data.pop('studentList') grade = Grade.objects.create(**validated_data) grade.school.set([sch]) #m2m field for student_data in student_datas: n1 = student_data["studentInfo"]["name"] r1 = student_data["studentInfo"]["rollNum"] student.objects.create(grade=grade, name=n1, rollNum=r1, schoolID = sch) return grade def update(self, … -
Django image is not uploading from the template, but uploads from admin
I am trying to create a page where the users can upload an image with their post. The image upload is working in another app, but in this one, whenever I submit the form, all the info except the image are inserted into the database. If I open the admin panel and upload an image, the image is uploaded successfully, it is only throught the template that I am not able to upload. Here is my model: def validate_image(image): file_size = image.file.size limit_mb = 3 if file_size > limit_mb * 1048576: raise ValidationError("Max size of file is %s MB" % limit_mb) class Posting (models.Model): poster = models.ForeignKey(User, related_name='poster_posting', verbose_name='poster') description = models.TextField(max_length=200, verbose_name=_('description')) pictures = models.ImageField( upload_to='postings/', verbose_name=_('Posting_picture'), blank=True, null=True, validators=[validate_image], ) def __str__(self): return "Posting #{}".format(self.pk) def filename(self): if self.pictures: return os.path.basename(self.pictures.name) return '' Here is the view: def posting(request): if request.method == "POST": form = Publish(request.POST) if form.is_valid(): post = form.save(commit=False) post.sender = request.user post.save() messages.success(request, _("your request was posted successfully")) if request.user.profile.disable_email_notification is False: send_user_notification( _('Send items request'), _( 'Hello {user}, <br> You just posted a request to send items from {source} to {destination} before {date} with the following description: <br> {description}. <br><br> we will now inform … -
Cant connect to local host after successfully able to run django project in pycharm
I am able to Run "manage.py" in My Django Project and it successfully runs too. But I am unable to connect to local host in my browser. What could have gone wrong , Please explain? -
How do I get my html template to correctly reference uploaded media content?
I'm trying to reference uploaded memes on my Django web app (development mode). I want "account" to reference "media/memes/images/{insert img}" but it's referencing "/account/media/memes/images/{insert img}". Below is account function in views.py: def account(request): user = request.user if user.is_authenticated: user_posts = Meme.objects.filter(author=request.user).order_by('-published') else: return _logout(request, timed_out=True) files = [m.file for m in list(user_posts)] #print("filenames to memes posted by user: ", files) return render(request, "account.html", context={"filenames": files}) Below is account.html: {% extends "layout.html" %} {% block content %} <div class="row"> {% for filename in filenames %} <br> <div class="col s12 m6 l4"> <div class="card-content"> <img src="media/{{ filename }}" width="80%" height="80%"></img> </div> </div> {% endfor %} </div> {% endblock content %} Below is the output: [07/May/2019 21:26:40] "GET /account/ HTTP/1.1" 200 1563 Not Found: /account/media/memes/images/michaeljordan.jpg [07/May/2019 21:26:40] "GET /account/media/memes/images/michaeljordan.jpg HTTP/1.1" 404 3418 -
How to make a Search section in html and search view in django with multiple queries
I am trying to do car sale webpage (educational purpose) and i found out how to make a search but i want to make it look better as it is in many car sale pages with section where it is possible to choose car categories, fuel type, damaged or not etc. my search view for now is this: def search(request): if 'search_filter' in request.GET: search_filter = request.GET['search_filter'] cars = [{ 'id': x.id, 'driven': x.driven, 'description': x.description, 'price': x.price, 'firstImage': x.carimage_set.first().image } for x in Car.objects.filter(description__icontains=search_filter) ] return JsonResponse({'data': cars}) context = {'cars': Car.objects.all().order_by('price')} return render(request, 'cars/car_index.html', context) Now, this perform search if it finds in the description, what I am looking. My goal is to make it so the user can enter the values that wants to search in the input box, like car type, car make, year etc. <!DOCTYPE html> <html> <body> <form action=""> <select name="cars"> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="fiat">Fiat</option> <option value="audi">Audi</option> </select> <legend>Additional Info:</legend> Car Type:<br> <input type="text" name="car_type"> <br> Car Make:<br> <input type="text" name="car_make"> <br><br> <input type="submit" value="Search"> </form> </body> </html> This is a very primitive form, but this is my idea of how i am trying to make it look like.