PyQt5 User accessing - pyqt5

We have a university system developed by pyqt5 and python, in the login interface, the instructor can log in by the id and pass, but after login, we have another interface to show the courses of the instructor based on the input id that was from previous interface, the problem that the interface of the courses does not show the courses for the instructor( the id is not accessible to next interface).
I noticed that each interface is not updated when we do action, what is the command to let interfaces' action linked together?
This is the code:
class InstructorLogin(QDialog):
def __init__(self):
super(InstructorLogin, self).__init__()
loadUi("NewInstructorLogin.ui",self)
self.LoginInst.clicked.connect(self.gotoAfterInstLogin)
self.ExitLoginInst.clicked.connect(self.gotoMainExit1)
self.PmuPassInstButton.setEchoMode(QtWidgets.QLineEdit.Password)
#For the password
def gotoAfterInstLogin(self):
global f
global user
user = self.PmuIDInstButton.text()
password = self.PmuPassInstButton.text()
# print(user)
if len(user)==0 or len(password)==0:
self.InvalidPassLab.setText("Please input all fields.")
else:
conn = sqlite3.connect("Cognito.db")
cur = conn.cursor()
query = 'SELECT Password FROM Instructor WHERE Instructor_id =\''+user+"\'"
cur.execute(query)
result_pass = cur.fetchone()[0] #to compare password
if result_pass == password:
self.gotoInstructorLoginAbulBashar()
#####end of noorsol
else:
self.InvalidPassLab.setText("Invalid username or password")
def gotoMainExit1(self):
widget.setCurrentIndex(widget.currentIndex()-1)
#Remove comment later
def gotoInstructorLoginAbulBashar(self):
widget.setCurrentIndex(widget.currentIndex()+15)
# def user_getter(self):
# return user
########################################################################################################################
class ChooseCourseInst(QMainWindow):
global user
def __init__(self):
super(ChooseCourseInst, self).__init__()
#self.afterObj = AfterInstructorLogin()
self.afterInstructorLogin = AfterInstructorLogin()
loadUi("CoursesChosenInt.ui",self)
widget.setCurrentIndex(widget.currentIndex()+4)
self.exitabulbashar.clicked.connect(self.gotoexitabulbashar)
#self.InstServButton.clicked.connect(self.gotoInstServButton)
self.coursesreq.activated.connect(self.gotoInstServButton)
#self.courses(user)
#print(user)
def courses(self):
self.instructorLogin = InstructorLogin()
conn = sqlite3.connect("Cognito.db")
query = 'SELECT DISTINCT Course_name FROM Course WHERE Instructor_id =\''+self.instructorLogin.gotoAfterInstLogin(user)+"\'"
cur = conn.cursor()
cur.execute(query)
final_result = [i[0] for i in cur.fetchall()]
for i in range(len(final_result)):
self.coursesreq.addItem(final_result[i])
def gotoexitabulbashar(self):
widget.setCurrentIndex(widget.currentIndex()-16)
def gotoInstServButton(self):
self.chosencourse = self.coursesreq.currentText()
self.afterInstructorLogin.labeltest.setText(self.chosencourse)
self.afterInstructorLogin.diplayInfo()
#self.afterInstructorLogin.labeltest.show()
widget.setCurrentIndex(widget.currentIndex()-11)
I tried to let the user id as global variable, and create object and call it from the previous class, it shows User not defined, but the i put it inside function and i call that function in another class, it is defined but the courses empty so i expect to know how to refresh interfaces to let the change in first interface reflected in the second

Related

Name of pattern where an object is stored by UUID

I am programming an application where I want to store Session information by a UUID. For this purpose, I wrote this code:
import uuid
class ObjectStore:
def __init__(self):
self.objects = {}
def add(self, obj):
uuid_value = uuid.uuid4() # UUID4 generates a random UUID
self.objects[uuid_value] = obj
return uuid_value
def retrieve(self, uuid):
return self.objects[uuid]
Is this structure a common pattern? If so, does it have a name?

How to set permissions for a POST request in ModelViewSet's

How can I write my own permission class for POST requests when using ModelViewSet?
I already tried to write my own permission_classe with no success. Even if my permission class is returning false it is still granting access to the post request
models.py
class Building(models.Model, HitCountMixin):
user = models.ForeignKey(User, on_delete=models.CASCADE) limit_choices_to=Q(country=2921044) | Q(country=798544), on_delete=models.SET_NULL) #<------------ Eltern Element
name = models.CharField(max_length=200, null=True, blank=True)
description = models.TextField(max_length=2000,null=True, blank=True)
facilities = models.TextField(max_length=2000, null=True, blank=True)
...
views.py
class BuildingImageViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows groups to be viewed or edited.
"""
serializer_class = BuildingImageSerializer
permission_classes = (permissions.IsAuthenticated, IsOwner,)
def get_queryset(self):
if self.request.user.is_authenticated:
return BuildingImage.objects.filter(building__user=self.request.user)
return None
permissions.py
class IsOwner(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
print("TEST")
return False
urls.py
router = routers.DefaultRouter()
router.register(r'buildingimages', myrest_views.BuildingImageViewSet, base_name="buildingimage")
If I I try to upload an image it is working, Why?
My IsOwner permission class is evaluated because I can see the print line with "TEST" in the console.
MY SOLUTION:
def has_permission(self, request, view):
if view.action == 'create':
building_url = request.POST.get('building')
building_path = urlparse(building_url).path
building_id = resolve(building_path).kwargs['pk']
building = Building.objects.get(id=building_id)
return building.user == request.user
return True
Pass list of classes, you used has_object_permission(), You need to write code inside has_permission() method.
permission_classes = [<class 'rest_framework.permissions.AllowAny'>]
you have to pass class that derive BasePermission class
permission.py
from rest_framework import permissions
class IsOwner(permissions.BasePermission):
def has_permission(self, request, view):
if <CONDITION>:
return True
else:
return False

Parameterized Variables for use in Assertion Groovy Script

Essentially, I am using SoapUI for some smoke testing and have created an assertion script that checks if there is data within an SQL database.
This test has to be ran on three different environments, each with their individual database credentials.
What I would like to do is create a Custom Property (or set of custom properties) in the test class that holds the three sets of database information to allow a tester to simply select which environment they're testing rather than having to change the hard-coded assertion script.
The code:
import groovy.sql.Sql
import oracle.jdbc.driver.OracleDriver
def con = Sql.newinstance('"server", "user",
"pass", "oracle.jdbc.driver.OracleDriver"')
def res = con.rows("select * from table1 where message_in = 'Bang'")
log.info(res[0])
con.close()
assert res[0] != null
You should firstly create global variables, to do this please follow the below steps:
Click onto the project link which is located at the left hand side of the screen as a tree view menu.
Click to the 'Custom Properties' tab, at the left down side
Click onto the + icon to add new property.
After creating the variables for the DB connection you can access them within the groovy script as below.
import groovy.sql.Sql
import oracle.jdbc.driver.OracleDriver
def dbServer = context.expand( '${#Project#dbServer}' )
def dbUser = context.expand( '${#Project#dbUser}' )
def dbPass = context.expand( '${#Project#dbPass}' )
def con = Sql.newinstance('dbServer, dbUser,
dbPass, "oracle.jdbc.driver.OracleDriver"')
def res = con.rows("select * from table1 where message_in = 'Bang'")
log.info(res[0])
con.close()
assert res[0] != null

Test fails in tests.py but succeeds in python shell

I'm a newbee to python and django and I can't figure out what I'm doing wrong here.
I have a Site object:
class Site (models.Model):
domain = models.CharField(max_length=30)
support_status = models.CharField(max_length=20, choices= SITE_SUPPORTED_STATUS, blank=False)
requests = models.IntegerField()
objects = SiteManager()
def __unicode__(self):
return u'%s %s' % (self.domain, self.support_status)
And a SiteManager object
class SiteManager(models.Manager):
def supported_site_counts(self):
i = self.filter(support_status__iexact="SUPPORTED").count()
return i
From the console, the method "supported_site_counts()" works just fine
>>(InteractiveConsole)
>>> from bookmark.models import Site, SiteManager
>>> Site.objects.supported_site_counts()
>>>>2012-05-18 18:09:20,027 DEBUG (0.001) SELECT COUNT(*) FROM "bookmark_site" WHERE
>>>>"bookmark_site"."support_status" LIKE SUPPORTED ESCAPE '\' ; args=(u'SUPPORTED',)
>>>>2012-05-18 18:09:20,028 DEBUG Got 1 supported site
>>>>1
But when it's called from a testcase, the count returns as 0
class SiteManagerTest(unittest.TestCase):
def test_supported_site_counts(self):
self.x = False
self.count = Site.objects.supported_site_counts()
logging.debug(self.count)
This is probably because the tests will set up a database separate from your development database to run the tests in. You will need to put testing data in to the testing database, either programmatically or using fixtures.

Deleting SQL data in associated OneToOneField model from admin

I've got a model that references another model via OneToOneField so that when you use Django's built-in delete_selected admin action, the associated model's data is not deleted. I'd like to write a custom admin action to delete the data in that associated model as well.
Here's my model:
class Party(models.Model):
TYPE_CHOICES=(
('P','Person'),
('O','Organization')
)
partyType = models.CharField(max_length=1, choices=TYPE_CHOICES)
name = models.CharField(max_length=100)
comment = models.CharField(max_length=500,blank=True)
accessIdCrossRef=models.IntegerField(blank=True, null=True)
mailingLists = models.ManyToManyField(MailingList)
inMainList=models.BooleanField(default=False)
inSubList=models.BooleanField(default=False)
class Meta:
db_table='party'
ordering=['name',]
def __unicode__(self):
return self.name
class Person(models.Model):
party = models.OneToOneField(Party, editable=False)
firstName=models.CharField(max_length=60)
lastName=models.CharField(max_length=60)
...
def save(self):
if None == self.party :
print 'Creating party for person'
p = Party()
p.partyType = 'P'
p.save()
self.party = p
# Get address to set party name used in list
city=""
state=""
postalCode=""
try:
partyAddress = PartyPostalAddress.objects.get(party=self.party)
address = partyAddress.postalAddress
city=address.city
state=address.state
postalCode=address.postalCode
except PartyPostalAddress.DoesNotExist:
pass
self.party.name = '%s, %s - %s, %s %s' %(self.lastName, self.firstName, city, state, postalCode)
self.party.save()
super(Person,self).save()
My assumption was to write a def delete() in my model like this:
def delete(self):
self.party.delete()
self.delete()
And an admin action like so:
class PersonAdmin(admin.ModelAdmin):
list_display = ('lastName','firstName')
search_fields = ('firstName', 'lastName')
actions=['really_delete_selected']
def get_actions(self, request):
actions = super(PersonAdmin, self).get_actions(request)
del actions['delete_selected']
return actions
def really_delete_selected(self, request, queryset):
for obj in queryset:
obj.delete()
if queryset.count() == 1:
message_bit = "1 person was"
else:
message_bit = "%s people were" % queryset.count()
self.message_user(request, "%s successfully deleted." % message_bit)
really_delete_selected.short_description = "Delete selected entries"
That deletes person.party and most of person, but throws an error because person's party OneToOneField is now empty. The specific error is:
"AssertionError at /admin/common/person/
Party object can't be deleted because its id attribute is set to None."
Any ideas? This, this, and this question are related, but only one of them utilizes the OneToOneField and he did that erroneously.
I am getting a feeling that it should be as simple as switching the sequence of deleting the two (unless you have tried this already). Since the person is associated with party, once you delete person, you cannot access party. Hence you should do
person.party.delete()
person.delete()
Got it cleaned up and working!
My model:
class Party(models.Model):
name = models.CharField(max_length=100)
...
class Person(models.Model):
party = models.OneToOneField(Party, editable=False)
firstName=models.CharField(max_length=60)
lastName=models.CharField(max_length=60)
def delete(self):
d = self.party.id
Party.objects.get(id__exact=d).delete()
My admin:
class PersonAdmin(admin.ModelAdmin):
actions=['really_delete_selected']
def get_actions(self, request):
actions = super(PersonAdmin, self).get_actions(request)
del actions['delete_selected']
return actions
def really_delete_selected(self, request, queryset):
for obj in queryset:
obj.delete()
if queryset.count() == 1:
message_bit = "1 person was"
else:
message_bit = "%s people were" % queryset.count()
self.message_user(request, "%s successfully deleted." % message_bit)
really_delete_selected.short_description = "Delete selected entries"
...