Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Auto scroll iframe window during StreamingHttpresponse
I've got a StreamingHttpResponse function that I am running inside of a iframe child the code for the iframe is below. The iframe, and function is working properly but the function sometimes returns a very long output and you either need to hold down "page down" or constantly use mouse wheel to see the latest and greatest output. I'd like for it to automatically scroll when html/text is received in the browser. I believe I might be restricted by an html or css solution? I'm not sure if jQuery or Javascript of some sort will process properly in the StreamingHttpResponse which is why I included Django as a related framework. I've tried a div style overflow auto scroll solution without success. Here's the iframe code: <iframe src="{% url 'landingpage' %}" frameBorder="0" name="botframe3" scrolling="yes" style="position: absolute; height: 70%; width: 100%;"></iframe> Here's the StreamingHttpResponse call: @condition(etag_func=None) def stageDevice(request, cmd, pk): pullID = Pull.objects.filter(pk=pk)[0] pullIDq = Pull.objects.filter(pk=pk) emailListqc = EmailList.objects.filter(ccqc='yes') emailListstg = EmailList.objects.filter(ccstg='yes') reqUser = User.objects.get(username=request.user.username) return StreamingHttpResponse(runSetup(pullID, pullIDq, reqUser), content_type='text/html') Here's the runSetup function: def runSetup(pullID, pullIDq, reqUser): yield "<html><head><title>Setup Phase</title>\n" yield "<link rel='stylesheet' href='/static/css/base.css'>\n" yield "<link rel='stylesheet' href='/static/css/style.css'>\n" yield "<link rel='stylesheet' href='https://bootswatch.com/4/cyborg/bootstrap.css'></head>\n" yield "<div>Attempting to setup for pull ID {0} - … -
returning email = None when updating / creating a new user from the admin panel
I just created a custom User Model and a custom User Manager. Now, I want to be able to update / create users from the django admin panel. It works perfectly fine from the django ORM, but when it comes to the admin panel, the USERNAME_FIELD ( which is set to email ) returns None after every time I'm trying to update or create a new user. Here is my Model and my Manager : class UserManager(BaseUserManager): #custom create_user method def create_user(self, email, password=None): if not email: raise ValueError('Users must have an email address') user = self.model( email = self.normalize_email(email) ) print(email) user.set_password(password) user.save(using=self._db) print(user) return user #Custom create_super_user method def create_superuser(self, email, password=None): user = self.create_user( email = email, password = password ) user.admin = True user.is_superuser = True user.is_staff = True user.save(using=self._db) return user class User(AbstractBaseUser): #setting up Choices for interest, Must add other fields ... #interests = MultiSelectField( # max_length = 2, # choices = INTERESTS_CHOICES #) #Setting up a Ranking System email = models.EmailField( max_length=50, unique=True, blank=False, null=False ) username = models.CharField( max_length=25, unique=True, null=True, blank=True ) date_joined = models.DateTimeField(auto_now_add=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=70) birth_date = models.DateField(null=True, blank=True) reputation = models.PositiveIntegerField(default=0) is_active = models.BooleanField(default=True) … -
Django: extend QuerySet with a default filter
I'm trying to implement a soft-delete model in my project. To that end, I want to be able to filter out deleted objects by default. At the same time, I want to keep all my QuerySet filters in one place and accessible as MyModel.objects. I also want to be able to chain my filtering methods, so I'm looking towards using MyQuerySet.as_manager() as the manager for such models. Thus it looks like I need to extend Django's QuerySet, but add a custom default filter. However, I can't figure out how to do that. The following code does not look like a great idea. class MyQuerySet(models.QuerySet): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self = self.filter(deleted=False) I also tried to figure out how to use Manager.from_queryset() for that purpose, but I still don't see how to make a manager that would be reusable, that is one that I could inherit from and be able to add my own QuerySet methods and still have the default filtering. -
Why we use serializers instead of full clean to validate models or should we use them interchangeably?
I am working on a API server which uses Django Rest Framework. I have been using model's clean method to validate my models and calling full clean in views. It does not work properly for every situation. I sense there are some mistakes in my logic. I have never used any serializer and don't know should i use it or not while using full clean. So my question is how can I validate my models in a proper way. -
Foreign keys in django
Ok so I have a table named Courses where CourseCode and Pattern act as composite primary key. Now in another table called delivery_methods same CourseCode and pattern should act as foreign key for their respective attributes in table Courses. So how can I do that in django model -
Can't login Django admin with valid user and password on development environment (runserver)
I can't log into Django with my valid username and password. Its giving me the standard error: "Please enter a correct username and password. Note that both fields may be case-sensitive." I have even tried to create a new admin with python manage.py createsuperuser but even then I can't log into the new staff account. I checked and made sure that I have a django_session table in my database, but the expire_date and before today. I am using Django 2.2 I haven't logged into this project in a few months so I am not sure if that has anything to do with it? Thanks so much in advance! -
Not able to import module from another packages in python 3.6
I want to import models.py file from gameplay package in player.views.py file but getting error: No module named game.gameplay I've already tried: from game.gameplay.models import Game from ..gameplay.models import Game The structure of my project is: project | | |--game(package) | | | |--gameplay(package) | | | | | |--__init__.py | | |--models.py | | | |--player(package) | | | | | |--__init__.py | | |--views.py | | | |--manage.py | |--venv -
Django CMS - cookie cutter : The form could not be loaded. Please check that the server is running correctly
I started learning web development at a company, and was tasked with making a simple app in cookiecutter django, and then integrating django-cms into it. I used django cookie-cutter to start a project, and then integrated django-cms into the project following this guide : https://github.com/pydanny/cookiecutter-django http://docs.django-cms.org/en/latest/how_to/install.html After some initial trouble, I managed to get it going. After that, the next step was to add my "polls" app to the project and integrate Django CMS in it aswell. For that I followed this tutorial : http://docs.django-cms.org/en/latest/introduction/03-integrating_applications.html#incorporate-the-polls-application I managed to get all the way to the end of the last link, and then on step 6, this happens. Every time I try to delete a plugin from my site, or when I click create on the CMS toolbar i get this error (note: if I log in to /admin, I can create the page, but not via the cms menu bar on the actual website) : The form could not be loaded. Please check that the server is running correctly. And in the console : Refused to display 'http://127.0.0.1:8000/cms_wizard/create/?page=5&language=en&edit&cms_path=/home/?edit&language=en&structure' in a frame because it set 'X-Frame-Options' to 'deny'. bundle.toolbar.min.js:1 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental … -
Why Union of two Django querysets not working
I have tried to get union of some queryset but got unexpected result. Can you please help me I have also check with How can I find the union of two Django querysets? but its not working as well. Here i have attached image to show my tries. in the above image i get four queryset( qs, qs1 , qs2, my_qs ) after filter BetDetails objects here i want to get result in my_qs And when i tried to merge/Union of the queryset got on blank queryset in my_qs While i have data in qs1 . expected result should be <QuerySet [<BetDeetails: BetDetails object (29)>]> But i got : <QuerySet []> I don't know why its showing this type of result. Can anyone please explain and guide me to get desired result. -
How to pass credentials with redux to django API
My Django API is protected as follows: class cars(ListAPIView): permission_classes = [ permissions.IsAuthenticated, ] I would like to get the data using redux, but I am not sure how to pass my credentials along with my redux call ? Here is my redux call export const Search_Results = (name, getState) => { return dispatch => { axios.get(`http://127.0.0.1:8000/api/?name=${name}`, tokenConfig(getState)) .then(res => { dispatch(presentResult(res.data)) }); } }; It returns an error, as it does not like how tokenConfig(getState)) is passed. When I am in that page I can clearly see there is a token using the dev_tools. When I remove the tokenConfig part from the call I get xhr.js:166 GET http://127.0.0.1:8000/api/auth/user 401 (Unauthorized) And when I remove permission class from the API, then I can get all the data using the same redux call. Here is the action for tokenConfig for the curious // Setup config with token - helper function export const tokenConfig = getState => { // Get token from state const token = getState().auth.token; // Headers const config = { headers: { "Content-Type": "application/json" } }; // If token, add to headers config if (token) { config.headers["Authorization"] = `Token ${token}`; } return config; }; -
How to paginate on distinct times value shows up in query set?
I have a model of songs, this table contains single tracks and album tracks. These are separated using a column which is true or false based on type of track. I am retrieving back the results of albums, however I need pagination so I am not getting back all results and slowing down query. But with albums and pagination I have some tracks from the last album get cut off and end up on page 2. How can I do pagination by the distinct amount of times an album shows up. Let's say I want to paginate 50 albums regardless of how many tracks they have. Each album track entry has a specific column which has the same exact value to connect them as an album. -
How to delete row with the least id using Django ORM?
I'm wondering what is the idomatic Django equivalent of: DELETE FROM article WHERE ID = ( SELECT Min( ID ) FROM article ) What I have tried is to retrieve the article with the lowest id article = Article.objects.all().order_by("-id")[:1] And then: Article.objects.filter(id=article.id).delete() But I'm wondering if there is more efficient/elegant way to do so? -
TemplateDoesNotExist at / for a Django compiled project using PyInstaller
I am trying to run a Django project using an EXE file compiled using Pyinstaller. But when I run the compiled .EXE file using this command I get TemplateDoesNotExist at /. dj.exe runserver localhost:8000 First I installed Pyinstaller using the command: pip install pyinstaller Then I installed OSGeo4W64 on my Windows 10 machine for GDAL. I added this in settings.py: import os if os.name == 'nt': import platform OSGEO4W = r"C:\OSGeo4W" if '64' in platform.architecture()[0]: OSGEO4W += "64" assert os.path.isdir(OSGEO4W), "Directory does not exist: " + OSGEO4W os.environ['OSGEO4W_ROOT'] = OSGEO4W os.environ['GDAL_DATA'] = OSGEO4W + r"\share\gdal" os.environ['PROJ_LIB'] = OSGEO4W + r"\share\proj" os.environ['PATH'] = OSGEO4W + r"\bin;" + os.environ['PATH'] os.environ['DJANGO_SETTINGS_MODULE'] = 'dj.settings' SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__)) TEMPLATE_DIRS = ( os.path.join(SETTINGS_PATH, 'templates'), ) GEOS_LIBRARY_PATH = r'C:\OSGeo4W64\bin\geos_c.dll' GDAL_LIBRARY_PATH = r'C:\OSGeo4W64\bin\gdal204.dll' I also generated a spec file using this command: pyi-makespec dj/manage.py And this is the generated manage.spec: # -*- mode: python ; coding: utf-8 -*- block_cipher = None a = Analysis(['dj\\manage.py'], pathex=['C:\\Users\\omen\\Desktop'], binaries=[], datas=[('app/templates','app/templates')], hiddenimports=[], hookspath=[], runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher, noarchive=False) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE(pyz, a.scripts, [], exclude_binaries=True, name='manage', debug=False, bootloader_ignore_signals=False, strip=False, upx=True, console=True ) coll = COLLECT(exe, a.binaries, a.zipfiles, a.datas, strip=False, upx=True, upx_exclude=[], name='manage') I added in datas the … -
how to fix this error in opencv django error:(-215:assertion failed) !_src.empty() in function 'cv::cvtcolor' in djang
im woking with my capstone project and im using django as the backend framework for face recognition attendance system using OPENCV, getting image and training the image are working perfectly, but when I start the system to detect faces in the camera it trows error. OpenCV(4.1.0) C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor' i need help please T_T im using python 3.6, django 2.2, opencv 4.1 def getattendance(request): if not os.path.exists('./ImagesUnknown'): os.makedirs('./ImagesUnknown') fname = "recognizer/trainingData.yml" if not os.path.isfile(fname): print("Please train the data first") exit(0) face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') cap = cv2.VideoCapture(0) print(cap.isOpened()) recognizer = cv2.face.LBPHFaceRecognizer_create() recognizer.read(fname) while True: ret, img = cap.read() gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3, 5) for (x,y,w,h) in faces: cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),3) ids,conf = recognizer.predict(gray[y:y+h,x:x+w]) profile = Profile.objects.get(id=ids) name = profile.first_name cid = str(profile.church_id) if conf < 50: cv2.putText(img, 'Name: '+name, (x+2,y+h+35), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,255),2) cv2.putText(img, 'ID no.: '+cid, (x+2,y+h+65), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,255),2) # Hour,Minute,Second=timeIn.split(":") # c.execute('INSERT OR IGNORE INTO attendance (name,cid,timeIn,date) VALUES (?,?,?,?)', (name,cid,str(timeIn),str(date))) # conn.commit() else: cv2.putText(img, 'Unkown', (x+2,y+h-5), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,255),2) noOfFile=len(os.listdir("ImagesUnknown"))+1 cv2.imwrite("ImagesUnknown/Image"+str(noOfFile) + ".jpg", img[y:y+h,x:x+w]) cv2.imshow('Face Recognizer',img) if cv2.waitKey(20) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() -
Django questionnaire with several score categories per answer
I am very new to Django (and definitely rusty with HTML) and basically went through the official tutorial a couple of times. I am planning on creating a simple questionnaire with a list of questions, these questions can have several answers and each answer has a specific score for various categories. In the end the points for each category are added and depending on the score a message is displayed. I am a bit stuck on how to display the answers for each question in a template however. I am also unsure how to calculate the final score: should I create a new class in my models to store the score? Or should I just do it in views.py (I would prefer this solution for now, I don't need to store the score in the DB and I don't need to login a user)? Here is what I have so far: models.py from django.db import models class Questionnaire(models.Model): questionnaire_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.questionnaire_text class Question(models.Model): questionnaire = models.ForeignKey(Questionnaire, on_delete = models.CASCADE) question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete = models.CASCADE) choice_text = models.CharField(max_length=200) C1 … -
Problem with the presentation of data from the database on the html page in Django
I have a problem creating something like this in the html file, of course based on the data from the database and using loop: Cycle_title1 post_title1 post_title2 post_title3 Cycle_title2 post_title1 post_title2 post_title3 where post_title are post titles which was added to subsequent cycles I tried do it in this way, but it return only one set of titles: #views cycles = Cycle.objects.filter(author=user) for cycle in cycles: c_post = Post.objects.filter(cycle__title__startswith=cycle.title) context = { 'posts': posts, 'user': user, 'u_form': u_form, 'p_form': p_form, 'cycles': cycles, 'c_post': c_post, } print(c_post) return render(request, 'users/profile.html', context) #html {% for cycle in cycles %} <h4>{{cycle.title}}</h4> {% for c in c_post %} <h5>{{ c.title }}</h5> {% endfor %} {% endfor %} #my_models: class Post(models.Model): title = models.CharField(max_length=50, unique=True) content = MDTextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) class Cycle(models.Model): title = models.CharField(max_length=200, unique=True) description = models.TextField(max_length=500, default="Brak opisu") date_created = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) posts = models.ManyToManyField(Post) -
Django Azure ad AADSTS50011: The reply url specified in the request does not match the reply urls configured for the application
I am trying to authenticate a user using azure active directory but I am getting `AADSTS50011: The reply url specified in the request does not match the reply urls configured for the application I am using django-microsoft-auth library. I have referred to multiple StackOverflow question regarding this but none of them resolve my issue. None of them are Django specific settings.py """ Django settings for mywebapp project. Generated by 'django-admin startproject' using Django 2.1.4. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'wi31*5al3v=&or_p354489830j)w_zr-)1^a$m*=@yo1l62nni' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ["*"] SITE_ID = 1 # Application definition INSTALLED_APPS = [ 'django.contrib.sites', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', 'microsoft_auth', ] 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 = 'mywebapp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', … -
Query on a model field? Is it possible in models.py?
I have a model called StudentProfile: class StudentProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) class_advisor = models.CharField(max_length=50) year = models.OneToOneField(YearLevel, on_delete=models.SET_NULL, null=True) section = models.OneToOneField(Section, on_delete=models.SET_NULL, null=True) what I want to happen is, class_advisor to only return and accpet User with is_teacher = True. by the way here's my User model: class User(AbstractUser): email = models.EmailField( max_length=254, unique=True, verbose_name='Email Address', blank=True ) is_student = models.BooleanField(default=False, verbose_name='Student') is_superuser = models.BooleanField(default=False, verbose_name='Administrator') is_teacher = models.BooleanField(default=False, verbose_name='Teacher') is_staff = models.BooleanField(default=False, verbose_name='Staff') is_registrar = models.BooleanField(default=False, verbose_name='Registrar') -
Django nginx 502 bed get way
I am learing nginx for django, i am running the server in locally with docker. this is my django_nginix.conf file : server { listen 80; listen [::]:80 default_server; server_name musicaldd.com; client_max_body_size 90M; location /media/ { root /home/pyking/cpd/musicaldd_back/storage/; } location /static/ { root /home/pyking/cpd/musicaldd_back/storage/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Host $host; proxy_redirect off; proxy_buffering off; proxy_pass http://djangoapp:8000/; } } When I run the server creating docker images and hit the URLs, it returns me 502-bed getaway timeout | nginix Can anyone tell me why this errors occuse, how can I fix this error It may stupid question but this is very serious to me, coz, i am new on Nginx, it will really much be appreciated if you help me to fix this -
Modifying HTML Elements with Python Dictionary in Beautiful Soup
I am getting 'NoneType' object does not support item assignment, when trying to modify HTML elements using Beatiful Soup and a Python dictionary. This is for a program that will create a HTML file from a template. The values to change are received from the user in a form. Here is the code I have at the moment data = { 'banner-url': ['src', request.POST.get('banner_url')], 'banner-link': ['href', request.POST.get('banner_link')], 'title-text': ['text', request.POST.get('title-text')] } # Loop through the data dictionary and let Beautiful Soup find element with ID's that match the data[key] for key, value in data.items(): _temp = soup.find(id=key).value[0] = value[1] I would like to modify HTML elements using keys and values in a Python dictionary. When I run the program I get the NoneType error instead of the element being modified. The error is on the line _temp = soup... -
NOT NULL constraint failed: users_user.email
I just created a custom user Model and a custom user manager. I'm able to create superuser with manage.py createsuperuser, but when it comes to update, delete or even create a new user on the admin panel, I have this wierd error : NOT NULL constraint failed: users_user.email I have no idea how to fix it and I'm just stuck. Here is my model and my manager : class UserManager(BaseUserManager): #custom create_user method def create_user(self, email, password=None): if not email: raise ValueError('Users must have an email address') user = self.model( email = self.normalize_email(email) ) print(email) user.set_password(password) user.save(using=self._db) print(user) return user #Custom create_super_user method def create_superuser(self, email, password=None): user = self.create_user( email = email, password = password ) user.admin = True user.is_superuser = True user.is_staff = True user.save(using=self._db) return user class User(AbstractBaseUser): #setting up Choices for interest, Must add other fields ... #interests = MultiSelectField( # max_length = 2, # choices = INTERESTS_CHOICES #) #Setting up a Ranking System email = models.EmailField( max_length=50, unique=True, blank=False, null=False ) username = models.CharField( max_length=25, unique=True, null=True, blank=True ) date_joined = models.DateTimeField(auto_now_add=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=70) birth_date = models.DateField(null=True, blank=True) reputation = models.PositiveIntegerField(default=0) active = models.BooleanField(default=True) rank = models.CharField(choices=RANKING_CHOICES, max_length=5, default="basic") is_staff = … -
Localstorage arrays to be saved in Database using Django
I am having problems with a certain code. I'm still new to Django and Jquery. So I have a form, and all the fields are stored directly in the database using the views.py in and I'm using self.request.POST['var'] for each element that I'm saving in the back end. It works, but my problem is, how can I store multiple arrays from local storage. Since, I'm also working with a modal where I'll enter certain values. The values are stored in an itemlist and publishes a table row, for each time I click add, in the modal. I want to get all those items/elements and save it in the database. I've tried to use the self.request.POST but i keep on getting an error like MultipleInvalid entry. I'll send my code here, thanks -
Python-Django FieldError: Cannot resolve keyword 'XXX' into field
I am trying to create a small tracking app with a number of foreign key relations between models. After completing with the migrations, while trying to access the list page for teammembers model, I am getting the following error: "Cannot resolve keyword 'date_last_modified' into field. Choices are: assigned_lead, current_status, date_of_joining, designation, email, first_name, id, last_name, location, project_team_member, ts_project_team_member" However, I am able to add new teammember record using the admin panel and also able to access detail view of other models as well. Below sharing the models.py file I am using. I am fairly new to django, any help appreciated. Thanks in advance. from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Project(models.Model): title = models.CharField(max_length=200) description = models.CharField(max_length=300) primary_contact1 = models.CharField(max_length=100) primary_contact2 = models.CharField(max_length=100) start_date = models.DateField() end_date = models.DateField() current_status = models.CharField(max_length=100) code = models.CharField(max_length=10) type = models.CharField(max_length=50) new_VS_existing = models.CharField(max_length=50) source = models.CharField(max_length=50) engagement = models.CharField(max_length=50) owner = models.ForeignKey(User, on_delete=models.CASCADE) date_created = models.DateTimeField(default=timezone.now) date_last_modified = models.DateTimeField(auto_now=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('project-detail', kwargs={'pk': self.pk}) class Teammember(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.CharField(max_length=50) location = models.CharField(max_length=50) designation = models.CharField(max_length=50) date_of_joining = models.DateField() current_status = models.CharField(max_length=50) … -
Django factory boy pass fuzzy attribute to related factory
I'm trying to keep the line_weight and line_price values consistent across both factories so that Order.total == OrderLine.ext_price but that's not the case. It seems that they randomize again in RelatedFactory. How can the values be random each time InvoiceFactory is called but pass the same values to InvoiceLineFactory? class InvoiceFactory(factory.DjangoModelFactory): class Meta: model = Order exclude = ('line_price', 'line_weight') line_price = factory.fuzzy.FuzzyInteger(1, 100) line_weight = factory.fuzzy.FuzzyInteger(1, 100) total = factory.LazyAttribute(lambda _: _.line_price * _.line_weight) line = factory.RelatedFactory( 'order.factories.InvoiceLineFactory', 'order', price=line_price, weight=line_weight ) class InvoiceLineFactory(factory.DjangoModelFactory): class Meta: model = OrderLine ext_price = factory.LazyAttribute(lambda _: _.weight * _.price) -
Permission class in Django
I use Django group permissions, I can assign some permission for users. Here is my test scenario: I have a Company Model, User1.hasPerm -> view_company, change_company, add_company, delete_company Permissions.py: class HasPermissions(permissions.BasePermission): def has_permission(self, request, view): if request.user.has_perm('MYAPP.view_company'): return True else: return False if request.user.has_perm('MYAPP.change_company'): return True else: return False if request.user.has_perm('MYAPP.add_company'): return True else: return False if request.user.has_perm('MYAPP.delete_company'): return True else: return False return True CompanyView.py: class CompanyViewSet(ModelViewSet): queryset = Company.objects.all() filter_class = CompanyFilter serializer_class = CompanySerializer permission_classes = [IsAuthenticated, HasPermissions] def get_queryset(self): if self.request.user.is_authenticated and self.request.user.is_active: company = Company.objects.filter(companyUser__exact=self.request.user) return company else: return Company.objects.all() I wrote HasPermissions function to control user permissions, and this function works only CompanyView. I want to make global this function for I can control all view. HasPermissions function is like hard coding, I want to change the more usable version to control all views. How can ı do this?