Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adjusting images in django
I am working on a django website, the code works pretty well but I'd like to make a few adjustments in order to make the web more professional. There's a section in the web called latest posts. Here's the code: <!-- Latest Posts --> <section class="latest-posts"> <div class="container"> <header> <h2>Latest from the blog</h2> <p class="text-big">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p> </header> <div class="row"> {% for obj in latest %} <div class="post col-md-4"> <div class="post-thumbnail"><a href="#"><img src="{{ obj.thumbnail.url }}" alt="..." class="img-fluid"></a></div> <div class="post-details"> <div class="post-meta d-flex justify-content-between"> <div class="date">{{ obj.date }}</div> <div class="category"> {% for cat in obj.categories.all %} <a href="#">{{ cat }}</a> {% endfor %} </div> </div><a href="#"> <h3 class="h4">{{ obj.title }}</h3></a> <p class="text-muted">{{ obj.overview }}</p> </div> </div> {% endfor %} </div> </div> </section> What you can see in the website is this: As you might have noticed, the images aren't adjusted and therefore, the text doesn't look aligned. Is there any code that can adjust this? -
django Count show different value after search
I simulate Instagram app. I have Followers, Actions models. Each action is done on a "follower". Many actions can point to one follower. class Follower(models.Model): identifier = models.BigIntegerField( _("identifier"), unique=True, null=False, blank=False) class ActionModel(models.Model): target = models.ForeignKey(Follower, verbose_name=_("Target"), on_delete=models.CASCADE) # username of the done-on action user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, ) # django user that performed the action is_followed_back = models.BooleanField(_("Followed Back"), null=True, blank=True) # is target followed back Admin panel: # Custom Admin for Follower model class FollowerAdmin(AdminAdvancedFiltersMixin, NumericFilterModelAdmin, SpecialActions): ... # Private method to count been_followed_counter def _get_been_followed_count(self, obj): return obj.been_followed_count _get_been_followed_count.short_description = 'Been Followed Count' _get_been_followed_count.admin_order_field = 'been_followed_count' # Private method to count follow_back_count def _get_follow_back_count(self, obj): return obj.follow_back_count _get_follow_back_count.short_description = 'Follow Back Count' _get_follow_back_count.admin_order_field = 'follow_back_count' I then override the get_queryset for followers: # Override queryset method to add count's def get_queryset(self, request): qs = super().get_queryset(request) qs = qs.annotate( been_followed_count=Count('actionmodel', filter=Q(actionmodel__user=request.user)) ).annotate( follow_back_count=Count( 'actionmodel', filter=Q(actionmodel__user=request.user) & Q(actionmodel__is_followed_back=True) ) ) I get really strange results in the admin panel: no search in panel USERNAME : lior___shahar BEEN FOLLOWED COUNT:5 FOLLOW BACK COUNT:5 This is the True VALUE in actions: Value in action But once I do SEARCH in FOLLOWERS for the username: After Search USERNAME : … -
Could someone please explain to me how much memory this algorithm uses?
userzip = userlocation.objects.get(userid=request.user.id) isstaff = User.objects.filter(is_staff=True) for x in isstaff: for y in userzip: if x.id == y.userid: trainers = isstaff return render(request, "trainerSearch.html", {'trainers':trainers}) I don't really understand space complexity and need to figure it out for this algorithm. An explanation would really be appreciated. I have been trying to figure it out for a while now and feel lost. -
My django project not finding the new app
There's this problem am having right now where there's no error in my code and yet the code won't run. Am still a newbie trying out something I developed a little django project and pushed to github, went to my pythonanywhere console and cloned it. Now I went back to console and created a new app ( startapp command) added to INSTALLED_APPS and added some lines of code in the new app. Problem is that the URLs in the new are not going through and even the ls command is not listing the app Is this a git issue? -
Show more button disappears after second press
I simply cannot see the problem here, images are being fetched from a postgres database using ajax and display on the website. We limit the images shown to 5 when the page loads initially but there's a load more button which is supposed to show 5 more images when clicked, which it does but only twice and then it disappears while there are still images to load. Could someone please detect a mistake because I can't seem too find it. Or help rewrite the methods. Thanks in advance. Here's the code: //////////////////////// FETCH SEARCH RESULTS ////////////////////////// const fetch_result = async (data) => { Site.spinner(true) // console.log(data) document.querySelector('html').classList.remove("fixed2") try { const response = await $.ajax({ method: 'GET', url: '/api/v1/creators/search/?' + data, data: {limit:3, offset:0} }) .then(response => response.data) clear_dom() console.log(response) display_results(response.results) Site.spinner(false) let showMore = document.querySelector('#show_more_btn') if (response.next) { showMore.classList.remove('hide') showMore.addEventListener('click', (ev) => { //ev.preventDefault(); showMore.disabled = true show_more_results(response.next) }) } else { showMore.classList.add('hide') } } catch (error) { if (error) { // console.log(error) Site.spinner(false) } } } //////////////////////// SHOW MORE SEARCH RESULTS ////////////////////////// const show_more_results = async (url) => { try { const response = await fetch(url, { method: 'GET' }) Site.spinner(false) if (response.status === 200) { const creators = … -
Remove file objects from children models on delete
My model File has as main purpose to link multiple files for one Invoice. class File(models.Model): invoice = models.ForeignKey(Invoice, related_name = 'files', on_delete = models.CASCADE) file = models.FileField(upload_to = 'storage/invoicing/') def delete(self, *args, **kwargs): self.file.delete() return super(File, self).delete(*args, **kwargs) When i delete one instance of my model File, the file stored in storage/invoicing is also deleted because of my modified delete() method. However, if i delete the instance from the parent model Invoice, the file is not deleted. Even with the File instance being removed from the database, the file is still acessable. How can i code the parent model to delete everything from the children model, including the files? I've searched a bit and i know that probably signals like post_delete can help me here, but i really don't know how to code it. -
Django Rest Framework serializing queryset fetchedn with value_list
I'm trying to query a specific column from my table. I've tried doing it with this team_lenDeserialized = RolesInTeam.objects.values_list('user_id', flat=True).filter(academic_year_id=9).filter(deleted=0) team_lenDict = RolesInTeamSerializer(team_lenDeserialized, many=True) team_len = orderedDictToJSON(team_lenDict.data) After that I run it through a function that converts it to JSON def orderedDictToJSON(orderedDict): return json.loads(json.dumps(orderedDict)) then I go and manipulate it further. However if I try to serialize and convert the team_lenDeserialized I get an error that states AttributeError: Got AttributeError when attempting to get a value for field `user_id` on serializer RolesInTeamSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `int` instance. Original exception text was: 'int' object has no attribute 'user_id'. This is my model for that table class RolesInTeam(models.Model): user_id = models.IntegerField() team_id = models.IntegerField() role_id = models.IntegerField() deleted = models.IntegerField() academic_year_id = models.IntegerField() class Meta: managed = False db_table = 'roles_in_team' and my serializer class RolesInTeamSerializer(serializers.ModelSerializer): class Meta: model = RolesInTeam fields = ['id', 'user_id', 'team_id', 'role_id', 'deleted', 'academic_year_id'] I have no clue what's happening or why it's not working. -
Deleting Migration Files and Getting django.db.migrations.exceptions.NodeNotFoundError:
I have deleted all of migration files and now I am trying to $ python manage.py makemigrations but it is returning django.db.migrations.exceptions.NodeNotFoundError: Migration notifications.0001_initial dependencies reference nonexistent parent node ('blog', '0012_auto_20201118_22 55') How should I fix this error and start migrating from the beginning? The reason for deleting the migration files is due to removing a function that kept returning an error due one of the migration files so I decided to start clean with them. Any ideas on what step I should take to start migrations and migrate again? -
Django PermissionRequiredMixin restricting access to specific users
I hope someone can assist me, i am trying to give custom permissions to a page/view to only 1 user with specific access/permissions. I have a model that looks like this: class Book(models.Model): id = models.UUIDField( primary_key = True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=200) author = models.CharField(max_length=200) price = models.DecimalField(max_digits=6, decimal_places=2) cover = models.ImageField(upload_to='covers/', blank=True) class Meta: permissions = [ ('special_status', 'Can read all books'), ] def __str__(self): return self.title def get_absolute_url(self): return reverse('books_detail', args=[str(self.id)]) And a view: class BooksDetailView( LoginRequiredMixin, PermissionRequiredMixin, DetailView): model = Book context_object_name = 'book' template_name = 'books/books_detail.html' login_url = 'account_login' permission_required = 'books.special_status' I have given the specific user permissions via admin console however any user other than admin is getting 403 Forbidden can anyone tell me how to fix this or what seems to be the problem -
How to get rid of Django security vulnerabilities warning signs in terminal
I have a simple Django project with a PostgreSQL backend and I can't seem to get rid of the Django security vulnerabilities warning signs on my terminal. Settings.py: import os ... ENVIRONMENT = os.environ.get('ENVIRONMENT', default = 'development') ... SECRET_KEY = os.environ.get('SECRET_KEY') DEBUG = int(os.environ.get('DEBUG', default=0)) ALLOWED_HOSTS = ['localhost', '127.0.0.1'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', ... 'HOST': 'db', 'PORT': 5432 } } if ENVIRONMENT == 'production': SECURE_BROWSER_XSS_FILTER = True X_FRAME_OPTIONS = 'DENY' SECURE_SSL_REDIRECT = True SECURE_HSTS_SECONDS = 3600 SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_PRELOAD = True SECURE_CONTENT_TYPE_NOSNIFF = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_REFERRER_POLICY = 'same-origin' docker-compose.yml: version: '3.8' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 environment: - SECRET_KEY="SECRET_KEY" - DEBUG=1 - ENVIRONMENT=development volumes: - .:/code ports: - 8000:8000 depends_on: - db db: image: postgres:12.3 volumes: - postgres_data:/var/lib/postgresql/data/ volumes: postgres_data: docker-compose-prod.yml: version: '3.8' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 environment: - SECRET_KEY="SECRET_KEY" - DEBUG=0 - ENVIRONMENT=production ports: - 8000:8000 depends_on: - db db: image: postgres:12.3 What I am running on the terminal: sudo docker-compose down sudo docker-compose -f docker-compose-prod.yml -f docker-compose.yml up -d --build sudo docker-compose exec web python manage.py check --deploy After running it "sudo docker-compose exec web python manage.py check --deploy", I … -
How can i handle overlaps, reservation and open/close times for a business with django?
Im working on a project that is for making reservations, the business that are registered have open and close times: open_times = [{opens: 09:00am, closes: 13:00}, {opens: 15:00am, closes: 21:00}] --> Naps are really common in Uruguay so everyone closes theirs business after lunch xD an between those times an user can make reservations. Which could be the best approach for this? I can make a new class like class OpenTimesRanges: open_time = models.DateTimeField() close_time = models.DateTimeField() business = models.ForeignKey('Business') and these 3 field are unique together? use pandas for handling overlaps between times and reservations? Any recomendations is appreciated -
Is there a way I can import java output to a form class in a CreatView on django?
I would like to create a view that will autofill the data in my html template from a button click. how can I do this? Is it possible? What kind of documentation is available on the subject? Thank you. I have included the template for the create_entry, Entry model, and CreateEntryView information. <!-- templates/forages/entry_new.html --> {% extends 'base.html' %} {% block content %} <h1>New Entry</h1> </br> <button class="btn btn-primary ml-2" onclick="getLocation()">Location</button> </br> <p id="location"></p> <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <button class="btn btn-success ml-2" type="submit">Save</button> <a href="{% url 'project_list' %}" class="btn btn-warning ml-2">Cancel</a> </form> <script> var x = document.getElementById("location"); function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else { x.innerHTML = "Geolocation is not supported by this browser."; } } function showPosition(position) { x.innerHTML = "</br>Latitude: " + position.coords.latitude + "</br>Longitude: " + position.coords.longitude; } </script> {% endblock content %} models.py class Entry(models.Model): project = models.ForeignKey(Projects, on_delete=models.CASCADE, related_name='entries') foraged_material = models.CharField(max_length=255, choices=FORAGED_MATERIALS ) short_comment = models.TextField(max_length=255, help_text="You may type a 255 char short description of your find or leave the current date and time.", default=datetime.datetime.now()) latitude = models.DecimalField( max_digits=11, decimal_places=8, null=True, blank=True) longitude = models.DecimalField(max_digits=11, decimal_places=8, null=True, blank=True) count = models.DecimalField(max_digits=14, decimal_places=3, null=True, blank=True) unit = models.CharField(max_length=56, … -
Problem to save values with signal in django
With this signal, i try to save the values on same table, but it save initial value (total_ht=0, total_tva=0, total_ttc=0) instead of values 10 20 30, and when i update the invoice without any changes, it s updated and it display the correct values. class Invoice(models.Model): date = models.DateField(default=timezone.now) total_ht = models.DecimalField(max_digits=20, decimal_places=2, default=0) total_tva = models.DecimalField(max_digits=20, decimal_places=2, default=0) total_ttc = models.DecimalField(max_digits=20, decimal_places=2, default=0) def calculate(self, save=False): total_ht = 0 total_tva = 0 total_ttc = 0 for invoiceitem in invoiceitems: total_ht += 10 total_tva += 20 total_ttc += total_ht + total_tva totals = { 'total_ht': total_ht, 'total_tva': total_tva, 'total_ttc': total_ttc, } for k,v in totals.items(): setattr(self, k, v) if save == True: self.save() return totals def invoice_pre_save(sender, instance, *args, **kwargs): instance.calculate(save=False) pre_save.connect(invoice_pre_save, sender=Invoice) -
Possible concurrent writing of csv file by pandas
My Python function, which uses the pandas library, is currently reading from a csv file and writing back to the same csv file. Because this function may be called by multiple users who are using my Django web app, is there a possibility of errors if those users all call my function at the same time? The amount of data per user is simply a single row of 3-4 columns, so I expect the probability of simultaneous execution to not be significant if the read/write operation only takes a few milliseconds. If there will be errors, imagine 1 million users on my app, how do I mitigate this? -
Static files django
I'm starting learn Django and I stop on one thing - static files. I tried like its below make changes in seetings and html but it doesnt load on the website. Please help me ! **settings.py:** STATIC_ROOT = '/PycharmProjects/django_kurs/filmyweb/static/' STATIC_URL = '/static/' STATICFILES_DIRS = ['django_kurs/filmyweb/static/',] **filmy.html:** {% load static %} <!doctype html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge,chrome=1"> <title>Document</title> <link rel="stylesheet" href="{% static 'moj.css' %}"> </head> Thank You in advance ! -
Django ForeinKey in template
I'm building a multivendor in django. I have a general Merchant table and products table. How can i use the merchant shop name in product template. models.py class Merchant(models.Model): shop_name=models.CharField(max_length=100) shop_address=models.CharField(max_length=100) class Product(models.Model): name = models.CharField(max_length=255, unique=True) merchant=models.ManyToManyField(Merchant) details.html {{product.name}} {{product.brand}} {{product.category__shop_name}} the shop_name is not appearing in the template. thanks beforhand. -
Django test client gives 404 when trying to get a public file from google cloud storage. Works fine when using requests lib
I have a public file on cloudstorage with public url = https://storage.googleapis.com/xyz/abc.pdf import requests requests.get(url) # gives status_code=200 But in django test, following gives 404 error: self.client.get(url) # status_code=404 -
Django - rating system database design
I'm trying to implement rating system for my Django app and got a little stuck on designing database for this. I haven't really used ManyToMany field until now, so I'm not really sure if it makes sense. And also when it comes to actual rating, I would just like to increment good/medium/bad by 1 and then just display, for example, good: 20x Could someone provide feedback on this? class Ratings(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ratings_from = models.ManyToManyField(User, related_name='ratings_from') book = models.ForeignKey(Book, on_delete=models.CASCADE) good = models.IntegerField(null=True, blank=True) medium = models.IntegerField(null=True, blank=True) bad = models.IntegerField(null=True, blank=True) comment = models.CharField(max_length=300)``` -
convert datetime to local in Django
In my postgresql db my datetime are stored as the following format: >>> p.publish datetime.datetime(2020, 12, 6, 6, 19, 36, 269492, tzinfo=<UTC>) now I want to display times locally using {% load tz %} {{ post.publish|local }} nothing happens. Then I tried to do it in the shell: pytz.utc.localize(p.publish,is_dst=None).astimezone(local_timezone) which gives me the following error: ValueError: Not naive datetime (tzinfo is already set) so my question is why it cannot convert timedate when tzinfo is already set, and how to get around it. Is it not the whole point to store data in data base with a certain timezone(here UTC) and then display it in different time zones when required? am I missing something here? -
User model costomization errors in django
I'm working in an app where I need to create multiple types of users with different permissions and hierarchy, but I get an errors about the models that I used. this is my models definition in models.py #models.py from django.db import models from django.contrib.gis.db import models from phonenumber_field.modelfields import PhoneNumberField from django.contrib.gis.db import models as gis_models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from .managers import EmployeeManager class Employee(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=128, blank=True) last_name = models.CharField(max_length=128, blank=True) registration_number = models.PositiveSmallIntegerField(unique=True, blank=False, null=False) email = models.EmailField() cni = models.CharField(max_length=18, blank=True) picture = models.ImageField(upload_to='DriversPictures/', max_length=100, blank=True) matricule_cnss = models.PositiveIntegerField(blank=True) driving_licence = models.PositiveIntegerField(blank=True) recruitment_date = models.DateField(auto_now=False, auto_now_add=False, blank=True) phone = PhoneNumberField(blank=True, help_text='numéro de telephone') adress = models.CharField(max_length=128, blank=True) city_id = models.ForeignKey('City', blank=True, null=True, on_delete=models.SET_NULL) region_id = models.ForeignKey('Region', blank=True, null=True, on_delete=models.SET_NULL) is_exploitation_admin = models.BooleanField(default=False) is_supervisor = models.BooleanField(default=False) is_controlor = models.BooleanField(default=False) is_driver = models.BooleanField(default=False) is_active = models.BooleanField(default=True) vehicle_id = models.ForeignKey('Vehicle', blank=True, null=True, on_delete=models.SET_NULL) USERNAME_FIELD = 'registration_number' REQUIRED_FIELDS = ['first_name', 'last_name'] objects = EmployeeManager() def __str__(self): return (self.registration_number, self.first_name, self.last_name) class Supervisor(Employee): zone_name = models.CharField(max_length=128, blank=True) class Driver(Employee): supervisor_id = models.ForeignKey('Supervisor', blank=True, null=True, on_delete=models.SET_NULL) class Controlor(Employee): supervisor_id = models.ForeignKey('Supervisor', blank=True, null=True, on_delete=models.SET_NULL) gaz_station_id = models.ForeignKey('GazStation', blank=True, null=True, on_delete=models.SET_NULL) class Vehicle(models.Model): serie = models.PositiveSmallIntegerField(unique=True, blank=True) matricule = models.CharField(max_length=18, … -
how to join two forms details using username as primarykey?
My forms.py looks like this:- class cust_login(forms.Form): Username = forms.CharField() Firstname = forms.CharField() Lastname = forms.CharField() Email_adress = forms.EmailField(widget=forms.EmailInput) Password = forms.CharField(widget=forms.PasswordInput) Password_Again = forms.CharField(widget=forms.PasswordInput) class Cust_address_details(forms.ModelForm): class Meta(): model = Cust_addres fields = ['Phone_no','house_no','building_name','street','area','city','state','pincode'] I want the Username to be unique and it should be the primary key connecting the two forms. So, that later on when I want to check the customer details. I only need to type the Username of the customer. my models.Py looks like class Cust_detail(models.Model): Firstname = models.CharField(max_length=30) Lastname = models.CharField(max_length=30) signup_Username = models.EmailField(max_length=40) signup_Password = models.CharField(max_length=15) class Cust_addres(models.Model): Phone_no = models.CharField(max_length=10) house_no = models.CharField(max_length=50) building_name = models.CharField(max_length=50) street = models.CharField(max_length=50) area = models.CharField(max_length=30) city = models.CharField(max_length=30) state = models.CharField(max_length=30) pincode = models.CharField(max_length=6) Please help me out I'm stuck on this for a few days. -
Django TinyMCE adding custom style formats
I would like to add a custom style format to the TinyMCE editor on my Python Django website, so I can set a block of text to have a custom CSS class. I am looking at the TinyMCE documentation on style_formats and have found this javascript snippet. How do I write this in Python so I can add this to my TINYMCE_DEFAULT_CONFIG? tinymce.init({ selector: 'textarea', style_formats: [ // Adds a h1 format to style_formats that applies a class of heading { title: 'My heading', block: 'h1', classes: 'heading' } ] }); -
Why am I getting pymongo ServerSelectionTimeoutError?
This is a small Django project using MongoDB as a database running with Docker. I am getting a pymongo ServerSelectionTimeoutError. docker-compose.yml I tried finding the solution with mongo shell using docker exec -it container_id bash but everthing seems fine in there. Command I use to start mongo shell inside a running container is mongo -u signals -p insecure I also tried to connect to this database using MongoDB Compass and it worked. I am able to connect to MongoDB Compass. Connection string is mongodb://signals:insecure@localhost:27017/webform. I am able to see all the collections in MongoDB Compass but my Django application is not able to connect with database. 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__))) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'kv2ischvghz-st=13_-=1d=8ffpjsb_pi*9n%agi)k8w*g+70)' DEBUG = True ALLOWED_HOSTS = ['*'] APPEND_SLASH=False # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'WebForm.signals', 'rest_framework', 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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 = 'WebForm.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', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'WebForm.wsgi.application' # Database … -
Django Apache2 - Target WSGI script cannot be loaded as Python module error - mod-wsgi
i'm trying to deploy a website on VPS. Before everything, i was having python version problem. The problem was not let me to install up to date Django version. I contacted support and they did updated python version to 3.7. After setting module installations, i did some test on port 8000 with venv and app was working. After the test, i did setup up Apache2. Right now it showing 500 Internal Server Error. I believe this is python version error I'll be so grateful and happy if you help me. Please feel free to ask me anything The Os: Distributor ID: Ubuntu Description: Ubuntu 16.04.7 LTS Release: 16.04 Codename: xenial Apache2 Error log sudo tail -f /var/log/apache2/error.log [Sun Dec 06 08:31:42.487403 2020] [core:notice] [pid 907:tid 139908822431616] AH00094: Command line: '/usr/sbin/apache2' [Sun Dec 06 08:31:55.848991 2020] [mpm_event:notice] [pid 907:tid 139908822431616] AH00493: SIGUSR1 received. Doing graceful restart [Sun Dec 06 08:31:55.914428 2020] [mpm_event:notice] [pid 907:tid 139908822431616] AH00489: Apache/2.4.18 (Ubuntu) mod_wsgi/4.3.0 Python/3.5.2 configured -- resuming normal operations [Sun Dec 06 08:31:55.914470 2020] [core:notice] [pid 907:tid 139908822431616] AH00094: Command line: '/usr/sbin/apache2' [Sun Dec 06 08:32:09.945999 2020] [wsgi:error] [pid 1009:tid 139908701574912] [remote 46.1.174.214:0] mod_wsgi (pid=1009): Target WSGI script '/home/alpcusta/diricangrup/diricangrup/wsgi.py' cannot be loaded as Python module. … -
How to check and see if an output contains the desired elements from any list or not?
I am trying to write tests for a particular app in django using the python's unittest library. def test_permissions_for_admin(self): admin = Group.objects.get(name='Administrator') permisisons = admin.permissions.all() admin_permissions = ['add_ipaddress', 'change_ipaddress', 'delete_ipaddress', 'view_ipaddress', 'add_subnet', 'change_subnet', 'delete_subnet', 'view_subnet'] for p in permissions: print(p.codename) for p in permissions: self.assertIn(p.codename, admin_permissions) The Above code prints this, OUTPUT: change_emailaddress delete_emailaddress view_emailaddress add_ipaddress change_ipaddress delete_ipaddress view_ipaddress add_subnet change_subnet delete_subnet view_subnet view_group change_organization change_organizationowner add_organizationuser change_organizationuser delete_organizationuser view_organizationuser add_user change_user delete_user view_user Whereas What I am trying to check is that, all the permissions present from the variable admin_permissions are present in this output or not. I have tried using the assertIn, assertEqual, & assertTrue methods but it doesn't seem to work here. Is there anything else I could look for or any method present which I am not aware of to solve such kind of issues.