Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ag-Grid - How to Access a Datasource?
I have a web application (Python Django) and want to display DB content using ag-Grid. I understand that the grid requires data in JSON format. So far, so good. What I am struggling to understand is, how do I connect to the DB to get content? Will I do this in my Django controller and pass a JSON to the template in which I further pass it to ag-Grid? Or, does ag-Grid handle the data connectivity using server side datasource? I presume it's the latter. But then I don't understand how to use the guide in the aforementioned link. My DB is a PostgreSQL so I need to manually establish a connection, extract the content and pass it on to ag-Grid? That seems to defeat the purpose of the datasource object though. Thanks -
Filtering Django Objects and displaying data to HTML
I have a Django web app which I want to do some basic filtering on. Basically, I have a social media like site where Users register their hobbies. What I want to do is have a filter where Users can choose to see only Male or Female users for now. Whilst I can do this in the Python Shell with the following code: from mainapp.models import Profile Users = Profile.objects.all().filter(gender = "Male") I am having trouble with implementing this in Django. Here is my models.py file: class Hobby(models.Model): name = models.CharField(max_length=50, default='') def __str__(self): return self.name class Profile(models.Model): user = models.OneToOneField( to=User, blank=True, null=True, on_delete=models.CASCADE ) gender = models.CharField(max_length=6, default='') age = models.CharField(max_length=3, default='') dob = models.CharField(max_length=10, default='') image = models.ImageField(upload_to='profile_images') hobbies = models.ManyToManyField(Hobby) The filter function which is in the Views.py file: def filter(user): other_users = Profile.objects.all() filter_results = other_users.filter(gender = "Male") context = { 'appname': appname, 'usersresults': filter_results } return render(request, 'mainapp/members.html', context) The Urls part: path('filter/', views.filter, name='filter'), And the HTML code: <ul> {% for user in usersresults %} <li> <a> {{user}}</a> </li> {% endfor %} </ul> However, this does not work as expected and does not return anything to the display. I am not sure why … -
Django view only returning primary key from field to template, no data
I have a model which has a column categories in a Product table, which has one entry, 'beds'. When I try to get a list of categories, or products (all of which have names, descriptions, etc), the only thing I can get returned is numbers. This is the relevant view from my views.py def product(request): template = loader.get_template('/home/user/webapps/webapp/my_site/main_page/templates/main_page/product.html') prods = xroduct.objects.values_list('product') context={'prods': prods} return HttpResponse(template.render(context)) This is my code within a django template to display data {% for instance in prods %} <li>{{ instance }}</li> {% endfor %} However, all that gets returned, going by HTML when viewing the webpage, is: <li>(2,)</li> <li>(1,)</li> There should be a lot more information returned. Names, descriptions, etc. Why is this not being returned via my view? -
Django - Limit choices to choose what are not chosen in admin form
I currently have a model as below: class Person(models.Model): GENERATION_CHOICES = ( (1, 'First generation'), (2, 'Second generation'), (3, 'Third generation'), (4, 'Fourth generation'), (5, 'Fifth generation'), ) last_name = models.CharField(max_length=50) middle_name = models.CharField(max_length=50, blank=True) first_name = models.CharField(max_length=50) generation = models.IntegerField(choices=GENERATION_CHOICES, default=False) gender = models.CharField(max_length=1, choices=(('M', 'Male'), ('F', 'Female')), blank=False, default=None) father = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL, related_name='children_of_father', limit_choices_to={'gender': 'M'}) mother = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL, related_name='children_of_mother', limit_choices_to={'gender': 'F'}) wife = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL, related_name='wife_of', limit_choices_to={'gender': 'F'}) husband = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL, related_name='husband_of', limit_choices_to={'gender': 'M'}) And in admin.py: class CustomPersonModelForm(forms.ModelForm): class Meta: model = Person fields = '__all__' def __init__(self, *args, **kwargs): super(CustomPersonModelForm, self).__init__(*args, **kwargs) self.fields['wife'].queryset = Person.objects.filter(generation=???) class PersonAdmin(admin.ModelAdmin): form = CustomPersonModelForm list_display = ['generation', 'last_name', 'gender'] I wonder how I can limit the choices for self.fields['wife'] to all people who have the same generation as the current one that's on screen to be created (not saved yet), and also only limit to all that have not been chosen. Thank you. -
Django: Why does my code let the user create a new account with an email address that has already been taken?
When I remove the following user = User.objects.get(username=request.POST['username']) it recognizes if user uses a taken email address when signing up and shows user a sign up error. However the below code does not throw any error on email address taken. How can I fix this? def signup(request): if request.method == "POST": # User has info and wants an account now! if request.POST['password1'] == request.POST['password2']: try: user = User.objects.get(username=request.POST['username']) email = User.objects.get(email=request.POST['email']) return render(request, 'accounts/signup.html', {'error': 'Email and or username has already been taken'}) except User.DoesNotExist: user = User.objects.create_user(request.POST['username'], email=request.POST['email'], password=request.POST['password1']) auth.login(request, user) return redirect('homepage') else: return render(request, 'accounts/signup.html', {'error': 'Passwords must match'}) # User wants to enter info return render(request, 'accounts/signup.html') -
Matching QuerySets in Django Testing
I have a Django application and in my testing I run this code: def test_search_keywords_logic(self): response = self.client.get(reverse('search-results'), { 'q': 'test11' }) nt.assert_equal(response.status_code, 200) nt.assert_equal(response.context['query_string'], 'test11') nt.assert_equal(response.context['total_results'], 1) nt.assert_equal(response.context['found_results'], True) qs = QuerySet(CaseStudy.objects.filter(title='test1')) nt.assert_queryset_equal(response.context['study_results'], qs) The last line: nt.assert_queryset_equal(response.context['study_results'], qs) gives me the error: AttributeError: 'QuerySet' object has no attribute '_meta' I'm not sure what it means. All I want to do is assert that the queryset returned in the context variable 'study_results' is a match to what I know it should be CaseStudy.objects.get(title='test1') should return the correct CaseStudy object as it's the only one in the test db. However, it doesn't seem to work. I also tried just comparing the response context 'study_results' to <CaseStudy: test1>and even tried wrapping it in a QuerySet(). It still didn't work, seemed to see my QuerySet() for test1 as the test1 string divided into a list of the single characters. I've tried using both nt.assert_equal() and nt.assert_queryset_equal() Neither work. What would be the proper/working way to have these assertions pass? I know the study_results context returns the CaseStudy: test1 in this case. I just can't seem to get it to match in the assertion. Since I'm getting it from objects.filter it's already a … -
Django APScheduler not executing jobs according to schedule with Apache and mod_wsgi
I have a Django project that uses django-apscheduler with the following configuration: Apache virtualhost WSGIPassAuthorization On WSGIScriptAlias / /some/app/wsgi.py WSGIDaemonProcess some-app \ user=someapp threads=15 display-name=some-app \ python-path=/some/app/venv/lib/python3.7/site-packages WSGIProcessGroup some-app Scheduled tasks from pytz import utc from apscheduler.schedulers.background import BackgroundScheduler from django_apscheduler.jobstores import DjangoJobStore, register_events, register_job from administration.scheduled_tasks import add_db_backup, delete_old_db_backups scheduler = BackgroundScheduler(timezone=utc) scheduler.add_jobstore(DjangoJobStore(), 'default') register_events(scheduler) @register_job(scheduler, 'cron', hour='0', minute='0') def db_backups_job(): add_db_backup() delete_old_db_backups() scheduler.start() As expected, the scheduled job is visible in Django admin. Also, the jobs execute sometimes, for example the daily job above has executed seven times during this month, although today is 15th and it should thus have executed 15 times. Note that I have restarted Apache during this time. This seems to be a process lifetime issue. It seems that the mod_wsgi process is suspended and thus APScheduler jobs cannot run. What is the lifetime of the mod_wsgi process? How can I assure that the jobs execute according to schedule or at least daily? -
How Do I Load A Comments Form within the Blog Object View ? Or can those things somehow be loaded independently?
So I am in the process of creating a custom comments app for Django == 2.1 And I'd like to know how to load both the existing blog entry, and the comment form that will store the ContentType as blog instead of one of the other models which it can be associated with. The Method Resolution Order demands that that the leftmost View or mixin will be the one that is searched first for missing methods not declared within that respective View, or those Views that call the super().get() method ( form example ). Therefore I have concluded that the View for the Blog app should have the following code. blog/views.py class BLogTechObjectView(SingleObjectMixin, TemplateResponseMixin, BlogTechView): model = Blog slug_url_kwarg = 'blogtitle' template_name = 'extendsBlog.html' context_object_name = 'blog' slug_field = 'blog_name' def get(self, request, *args, **kwargs): blog = self.get_object() return render(request, 'extendsBlog.html', {'blog':blog}) comments/models.py class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') timestamp = models.DateTimeField(auto_now_add=True) content = models.TextField() def __str__(self): return '{} made this comment on : {} '.format(self.user, self.timestamp) def __unicode__(self): return '{} made this comment on : {} '.format(self.user, self.timestamp) comments/views.py class CommentFormView(generic.CreateView): form_class = CommentForm success_url = None template_name … -
FATAL: password authentication failed for user / but user exist
I'm banging my head against a wall here. I need another set of eyes. This is error I get: django.db.utils.OperationalError: FATAL: password authentication failed for user "localproject" FATAL: password authentication failed for user "localproject" I have set up the database like this in the settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'project', 'USER': 'localproject', 'PASSWORD': 'MahPassword', 'HOST': 'localhost', 'PORT': '', } } And I have created the Scheme like this: postgres=# CREATE DATABASE project; Set the user like this: postgres=# CREATE USER localproject WITH PASSWORD 'MahPassword'; Set the priviligies for the scheme like this: postgres=# GRANT ALL PRIVILEGES ON DATABASE project TO localproject ; And the database list looks like this: postgres=# \l List of databases Name | Owner | Encoding | Collate | Ctype | Access privileges -----------+----------+----------+-------------+-------------+------------------------ project | postgres | UTF8 | en_CA.UTF-8 | en_CA.UTF-8 |=Tc/postgres + | | | | | postgres=CTc/postgres + | | | | | localproject=CTc/postgres Why on earth do I get the error? -
Django: Show View after password entry
How can I return a View only after letting the user enter a password which is checked against the link? class Foo(models.Model): url = models.CharField(max_length=10) #a randomly created ASCII-string name = models.CharField(max_length=10) password = models.CharField(max_length=10) url_patterns = [path('foo/<url>/admin', views.foo, name='foo_admin'),] So a user goes to url: localhost/foo/bar now he should enter the correct password to see the content of model Foo with url='bar'. -
How to map an existing python class to a Django model
I'm writing a web scraper to get information about customers and appointment times to visit them. I have a class called Job that stores all the details about a specific job. (Some of its attributes are custom classes too e.g Client). class Job: def __init__(self, id_=None, client=Client(None), appointment=Appointment(address=Address(None)), folder=None, notes=None, specific_reqs=None, system_notes=None): self.id = id_ self.client = client self.appointment = appointment self.notes = notes self.folder = folder self.specific_reqs = specific_reqs self.system_notes = system_notes def set_appointment_date(self, time, time_format): pass def set_appointment_address(self, address, postcode): pass def __str__(self): pass My scraper works great as a stand alone app producing one instance of Job for each page of data scraped. I now want to save these instances to a Django database. I know I need to create a model to map the Job class onto but that's where I get lost. From the Django docs (https://docs.djangoproject.com/en2.1/howto/custom-model-fields/) it says in order to use my Job class in the Django model I don't have to change it at all. That's great - just what I want. but I can't follow how to create a model that maps to my Job class. Should it be something like from django.db import models import Job ,Client class JobField(models.Field): description … -
Django Form Not Rendering HTML from class HomeForm
For some reason I cannot get my Django form to render. I'm not sure what I'm missing. I'm trying to get the class HomeForm(forms.Form) to render on the myaccount/change.html page and have been unsuccessful. I'm new to Django so I might be missing a small detail somewhere but I thought I got everything covered from the djago documentation. If anyone can help me out it would be gladly appreciated. Thanks! users/forms.py from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django import forms from .models import CustomUser class HomeForm(forms.Form): post = forms.CharField() your_name = forms.CharField(label='Your name', max_length=100) class CustomUserCreationForm(UserCreationForm): # job_title = forms.IntegerField(label='2 + 2', label_suffix=' =') # yes = forms.IntegerField(required=True) tos_check = forms.BooleanField(required=True, label='I have read and agree to the Terms of Service.') age_check = forms.BooleanField(required=True, label='I am 21 years of age or older.') class Meta(UserCreationForm.Meta): model = CustomUser fields = ('username', 'email') help_texts = { 'username': '', 'email': '', # 'password1': 'None', # 'password2': 'Test' } class CustomUserChangeForm(UserChangeForm): tos_checktwo = forms.BooleanField(required=True, label='I have read and agree to the Terms of Service.') class Meta(UserChangeForm.Meta): model = CustomUser fields = ('username', 'email', 'tos_checktwo') # class Meta: # model = CustomUser # fields = ('username', 'email', 'tos_check',) users/views.py from django.http import HttpResponse from django.http … -
Ignoring Test Files with Nose/unittest
I have two test files. One is standard TestCases. The other has selenium tests in it. I have a docker-compose file setup to run the selenium tests with their associated services. The tests run in bitbucket-pipelines. First it runs the test with the standard TestCases. Then in the next step it uses docker-compose to run the tests that include selenium since it needs compose to set up the selenium services. The issue I'm having is it's trying to run the selenium tests during the first step when there isn't any selenium containers running. I entered this in my Django settings file used for the first testing part: NOSE_ARGS = [ '--exclude=(__init__.py)', '--exclude=(../tests/selenium_tests.py)', '--exclude=(selenium_tests.py)', '--with-coverage', '--cover-package=sasite', '--with-xunit', '--xunit-file=test-results/nose/noseresults.xml', '--verbosity=3', '--cover-xml', '--cover-xml-file=test-results/nose/noseresults.xml', '--id-file=test-results/nose/noseids' ] and in my settings for the second: NOSE_ARGS = [ '--exclude=(__init__.py)', '--with-coverage', '--cover-package=sasite', '--with-xunit', '--xunit-file=test-results/nose/noseresults.xml', '--verbosity=3', '--cover-xml', '--cover-xml-file=test-results/nose/noseresults.xml', '--id-file=test-results/nose/noseids' ] As you can see, I want to exclude the selenium tests for the first part, and use them for the second. But even with my exclude in nose_args it still runs the selenium tests in the first part. Here is my bitbucket-pipelines.yml: prod-final: - step: name: Build image, run tests, and push to Docker Hub caches: - docker … -
page is not opening by giving url django
I am unable to show purchasing template by writing URL "purchaing" on browser. I am beginner here. modelform venv projectforms urls.py bookingform urls.py views.py projectforms.urls from django.contrib import admin from django.urls import path, include from django.conf.urls import include, url urlpatterns = [ path('admin/', admin.site.urls), path('',include('bookingform.urls')), path('purchasing/', include('bookingform.urls')), ] bookingform.urls from django.urls import path from . import views urlpatterns = [ path('',views.add_model), path(r'^purchasing/',views.purchasing_view,name="purchasing"), ] bookingform.views def purchasing_view(request): if request.method == "POST": purchasing_form = purchasingform(request.POST) if purchasing_form.is_valid(): purchasing_form.save() messages.success(request, 'Purchaing Record Saved') # return redirect('/') return render(request, "purchasing.html", {'purchasing_form': purchasing_form}) else: purchasing_form = purchasing() # purchaing = purchasing.objects.all() return render(request, "purchaing.html", {'purchasing_form': purchasing_form}) -
Materialize sidenav not working in Django
I am able to see the hamburger icon which appears when the screen is made smaller, but when I press it is unresponsive. This is the code for my base.html file {% load static %} <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <!-- Compiled and minified CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> <!-- Materialize icons --> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> {% block head %} <title>Home</title> {% endblock %} </head> <body> <!-- navbar --> <nav> <div class="nav-wrapper"> <a href="#!" class="brand-logo center">Logo</a> <a href="#" data-target="mobile-demo" class="sidenav-trigger"><i class="material-icons">menu</i></a> <ul class="right hide-on-med-and-down"> <li><a href="sass.html">Sass</a></li> <li><a href="badges.html">Components</a></li> <li><a href="collapsible.html">Javascript</a></li> <li><a href="mobile.html">Mobile</a></li> </ul> </div> </nav> <!-- hamburger icon side navbar --> <ul class="sidenav" id="mobile-demo"> <li><a href="sass.html">Sass</a></li> <li><a href="badges.html">Components</a></li> <li><a href="collapsible.html">Javascript</a></li> <li><a href="mobile.html">Mobile</a></li> </ul> <script> $(document).ready(function(){ $('.sidenav').sidenav(); }); </script> {% block body %} <h1>Base</h1> {% endblock %} <!-- Compiled and minified Jquery --> <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> <!-- Compiled and minified JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"> </script> </body> </html> I also have a js folder in static folders with materialize.js inside. Although I'm unsure what's supposed to go there. I've tried using various versions of jQuery but nothing has worked so far. I made a responsive navbar in bootstrap with no problems so not sure what … -
Django template rendering under a wrong URL
Im working on an application (to learn django) where it has kind of master template. and the view.py @login_required def home(request): return render(request, '../templates/mainSection/home.html') def createshipment(request): if request.method == "GET": # shipmentNumber is defined by 'SHN-000' + next Id in the shipment Table try: # trying to retrive the next primaryKey nextId = Shipment.objects.all().count() nextId += 1 except: # if the next ID is null define the record as the first nextId = 1 # creating the form with the shipment ID form = CreateShipmentForm(initial={'shipmentNumber':'SHN-000' + str(nextId)}) return render(request, '../templates/mainSection/createshipment.html', {'form': form}) def saveshipment(request): if request.method == 'POST': form = CreateShipmentForm(request.POST) if form.is_valid(): try: form.save() except (MultiValueDictKeyError, KeyError) as exc: return HttpResponse('Missing POST parameters {}'.format(exc), status=400) else: messages.error(request, form.errors) return render(request, '../templates/mainSection/fillshipment.html') def viewshipment(request): return render(request, '../templates/mainSection/viewshipment.html') def fillshipment(request): if request.method == "GET": # creating the form productForm = CreateProductForm() # Retrieving The Product types for the ShipmentForm productType_list = ProductTypes.objects.all() shipment_list = Shipment.objects.all() return render(request, '../templates/mainSection/fillshipment.html', {'productTypes': productType_list, 'shipments': shipment_list, 'productForm': productForm}) and the urls.py urlpatterns = [ path('home/', views.home,name="home"), path('home/createshipment/',views.createshipment,name="createshipment"), path('home/createshipment/saveshipment/',views.saveshipment,name="saveshipment"), path('home/fillshipment/',views.fillshipment,name="fillshipment"), path('home/viewhipment/',views.viewshipment,name="viewshipment"), ] The problem that Im trying to solve is, After submitting a form and navigating to the next, the template diffrent under the previous URL. … -
Django - loop using models.PositiveIntegerField variable
I have this code: class Zapas(models.Model): tym_domaci = models.ForeignKey(Tym, on_delete=models.CASCADE) tym_hoste = models.ForeignKey(Tym, on_delete=models.CASCADE) datum = models.DateTimeField('datum zapasu') goly_domaci = models.PositiveIntegerField(default=0) goly_hoste = models.PositiveIntegerField(default=0) for x in range (goly_domaci): strelec = models.ForeignKey(Hrac, on_delete=models.CASCADE, limit_choices_to={Hrac.tym == tym_domaci}) nahraval = models.ForeignKey(Hrac, on_delete=models.SET_NULL, blank=True, null=True, limit_choices_to={Hrac.tym == tym_domaci}) for x in range (goly_hoste): strelec = models.ForeignKey(Hrac, on_delete=models.CASCADE, limit_choices_to={Hrac.tym == tym_hoste}) nahraval = models.ForeignKey(Hrac, on_delete=models.SET_NULL, blank=True, null=True, limit_choices_to={Hrac.tym == tym_hoste}) What i am trying to do, is to load all the players that scored a goal and players that assisted on it (if there is any) for each team. Problem is, that i cannot use goly_domaci and goly_hoste in the for loop because they are PositiveIntegerField and not an Integer. Is there any way to convert the PositiveIntegerField into Integer? Or can I even use the for loop like this? I am new to python and Django so I really dont know how to solve it. Thanks for help :-) -
How to arrange posts from different models in Order of time when they were created
Intro: I have a 3 models user, post, group. User is able to make posts however each post has to belong to a group. I have 400 fixed groups. Users have to choose from the existing 400 groups for their posts. Users cannot add, delete, update group's. Furthermore: Users can become a member of groups and when they click on a certain group. They see all the posts in that group. Users can follow-unfollow other users. **What I have right now:**When a user signs-in. In his home page he sees. All the posts of the each individual group he is a member of. When all the posts from all the groups are done with. He then sees the posts of all the people he follows one by one What I want: I want the posts to be arranged by time Example: If one of the people he follows just wrote a post then that post is first. Chronologically the second post was in one of the groups that he is a member of. That post comes second... You get the idea Below are my models class Post(models.Model): user = models.ForeignKey(User, related_name='posts') group = models.ForeignKey(Group, related_name='posts') title = models.CharField(max_length=250, unique=True) message … -
Lost old data after add new data Django Admin
class Song(models.Model): song_id = models.AutoField(default=1,primary_key=True,editable=False) file = models.FileField(upload_to=only_filename,null=True,blank=True) name = models.CharField(max_length=50) album_id = models.ForeignKey(Album, on_delete=models.CASCADE) lyric = models.TextField() cover_imagemodels.ImageField(upload_to="img/",default="img/None/icon.jpg") listen_time = models.PositiveIntegerField(default=0,editable=False) def __str__(self): return self.name Above is my class model. First, I login to superuser in Django Admin, then add a new song. It's success. But, after that I continue add another song, there is only a newest song is saved, and older song dispear. I use mysql command line to check and there is only newest one is exist. How to fix it? Sorry for my bad english. -
Selenium Testing - Test if Clicking Button Opens Correct Items
I have two buttons on my page, one for viewing a pdf (opens in new tab) and one for downloading pdf (downloads it directly by adding the attachment header. Here's my testing code so far: def test_study_popover_view_clicked(self): cls.selenium_chrome.get('https://www.shenkan-associates.com/') try: target_element_chrome = cls.selenium_chrome.find_element_by_id('study-item-7') target_element_chrome.click() popover_element_chrome = cls.selenium_chrome.find_element_by_class_name('popover') popover_view_button_element_chrome = cls.selenium_chrome.findElement(By.cssSelector('.popover > .popover-content > .popover-actions > .study-view')) except NoSuchElementException as ex: self.fail(ex.msg) nt.assert_true(popover_element_chrome.is_displayed()) nt.assert_true(popover_view_button_element_chrome.is_displayed()) nt.assert_equal(popover_view_button_element_chrome.text, 'View') popover_view_button_element_chrome.click() def test_study_popover_download_clicked(self): cls.selenium_chrome.get('https://www.shenkan-associates.com/') try: target_element_chrome = cls.selenium_chrome.find_element_by_id('study-item-7') target_element_chrome.click() popover_element_chrome = cls.selenium_chrome.find_element_by_class_name('popover') popover_download_button_element_chrome = cls.selenium_chrome.findElement(By.cssSelector('.popover > .popover-content > .popover-actions > .study-download')) except NoSuchElementException as ex: self.fail(ex.msg) nt.assert_true(popover_element_chrome.is_displayed()) nt.assert_true(popover_download_button_element_chrome.is_displayed()) nt.assert_equal(popover_download_button_element_chrome.text, 'Download') popover_download_button_element_chrome.click() As you can see I click the download and view button elements. at the end of each method. Clicking view should open a pdf in a separate tab. Clicking download should start to download the pdf directly. I just need a way to test that the buttons are doing what they should. How can I test this? Thanks -
TypeError: __init__() got an unexpected keyword argument 'topic'
while i was adding value to a query set i got this this error. models.py from django.db import models class Topic(models.Model): def __init__(self): topic=models.CharField(max_length=264,unique=True) def __str__(self): return self.topic class Webpage(models.Model): def __init__(self): topic=models.ForeignKey(Topic) name=models.CharField(max_length=264,unique=True) url=models.URLField(unique=True) def __str__(self): return self.name class AccessRecord(models.Model): def __init__(self): name=models.ForeignKey(Webpage) date=models.DateField() def __str__(self): return str(self.date) #t=Topic(topic="shoaib") Traceback (most recent call last): File "<console>", line 1, in <module> TypeError: __init__() got an unexpected keyword argument 'topic' -
Why am I getting an UnorderedObjectList Warning even though I'm following a conventional usage of the order_by() function?
I have a generic list view from which I paginate using the querysets from two separate models : Message and safeTransaction. django terminal output gives this warning upon entry to my inbox view : /usr/local/lib/python3.6/dist-packages/django/views/generic/list.py:88: UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list: QuerySet. allow_empty_first_page=allow_empty_first_page, **kwargs) This is the View and get_context_data method : ### Inbox list class class InboxListView(ListView): #This view lets the user view all the messages created in a list model = Message template_name = "myInbox/inbox.html" paginate_by = 3 # paginating twice here #so the page gets paginated in a convenient way for my template. def get_context_data(self, **kwargs): message_list = Message.objects.filter(recipient=self.request.user) .order_by('-date') safeTransaction_list = SafeTransaction.objects .filter(trans_recipient=self.request.user) .order_by('-date') queryset = list(chain(message_list, safeTransaction_list)) #paginator setup start paginator = Paginator(queryset,3) page = self.request.GET.get('page') safe_T_list = paginator.get_page(page) #iterable list for template #paginator setup done context = super(InboxListView, self).get_context_data(**kwargs) context.update({ 'now': timezone.now(), 'message_list':safe_T_list, }) return context What I am doing in this method is chaining the filtered querysets into a list, then paginating that as one queryset. The problem is that even before I do that, my filtered Messages and SafeTransactions are seen as unordered lists. This confuses me because the typical usage of order_by() on the django website is … -
is it necessary to implement ModelForm in our project to implement a CreateView (CBV) in Django 2.0.2?
I am a beginner programming in Django framework and I am learning how to implement a CreateView (a class based view for creating a form based on a model) in my views.py file. -
Python django Need return name instead of id foreginkey
class Product(models.Model): name = models.CharField(max_length=300, default='default name') description = models.TextField(max_length=800, blank=True, null=True) link = models.TextField(default='0') type = models.ForeignKey(ProductType, on_delete=models.CASCADE, null=True, blank=True) category = models.ForeignKey(ProductCategory, on_delete=models.CASCADE, null=True, blank=True) keyword = models.OneToOneField(KeyWords, on_delete=models.CASCADE, null=True, blank=True) model don't return data from ForeignKey -
why don't save password in my database of Django
i work with Django. i use AbstractBaseUser for create User in models. i create form's for my models . my forms don't save password in my database Forms: from django import forms from django.contrib.auth import get_user_model class Register(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput) class Meta: User = get_user_model() model = User fields = ('username', 'number' , 'country' , 'city' , 'email') def clean_username(self): User = get_user_model() username = self.cleaned_data.get('username') qs = User.objects.filter(username=username) if qs.exists(): raise forms.ValidationError("username is taken") return username def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 class UserAdminCreationForm(forms.ModelForm): """A form for creating new users. Includes all the required fields, plus a repeated password.""" password = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: User = get_user_model() model = User fields = ('username', 'number' , 'country' , 'city' , 'email') def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): # Save the provided password in hashed format user = …