Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Centos + apache Error client denied by server configuration: Call to fopen() failed for to my wsgi.py
I have simple django application running in centos. It runs fine with built-in django server (python manage.py runserver). The error comes when I try to run with apache. [Thu Dec 27 09:41:42.484517 2018] [:error] [pid 6104] (13)Permission denied: [remote 10.0.2.2:0] mod_wsgi (pid=6104, process='myproject', application='localhost.localdomain:8017|'): Call to fopen() failed for '/home/vagrant/myproject/myproject/wsgi.py'. have changed ownership and 777 permission to be apache user from /home till /home/vagrant/myproject/myproject/wsgi.py below is my apache configuration <Directory /home/vagrant/myproject/static> Require all granted AllowOverride None </Directory> <Directory /home/vagrant/myproject/myproject> Order allow,deny Allow from all # New directive needed in Apache 2.4.3: Require all granted <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-path=/home/vagrant/myproject:/home/vagrant/myproject/myprojectenv/lib/python2.7/site-packages WSGIProcessGroup myproject WSGIScriptAlias / /home/vagrant/myproject/myproject/wsgi.py and this is my wsgi.py file import os import sys # Add the site-packages of the chosen virtualenv to work with site.addsitedir('/home/vagrant/myprojectenv/local/lib/python2.7/site-packages') # Add the app's directory to the PYTHONPATH sys.path.append('/home/vagrant/myproject') sys.path.append('/home/vagrant/myproject/myproject') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings") # Activate your virtual env activate_env="/home/vagrant/myprojectenv/bin/activate_this.py" execfile(activate_env, dict(__file__=activate_env)) from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings") application = get_wsgi_application() between I tried many solutions suggested by similar other stackoverflow suggestions. But no luck. Thanks in advance. -
Can I define classes in Django settings, and how can I override such settings in tests?
We are using Django for Speedy Net and Speedy Match (currently Django 1.11.17, we can't upgrade to a newer version of Django because of one of our requirements, django-modeltranslation). I want to define some of our settings as classes. For example: class UserSettings(object): MIN_USERNAME_LENGTH = 6 MAX_USERNAME_LENGTH = 40 MIN_SLUG_LENGTH = 6 MAX_SLUG_LENGTH = 200 # Users can register from age 0 to 180, but can't be kept on the site after age 250. MIN_AGE_ALLOWED_IN_MODEL = 0 # In years. MAX_AGE_ALLOWED_IN_MODEL = 250 # In years. MIN_AGE_ALLOWED_IN_FORMS = 0 # In years. MAX_AGE_ALLOWED_IN_FORMS = 180 # In years. MIN_PASSWORD_LENGTH = 8 MAX_PASSWORD_LENGTH = 120 PASSWORD_VALIDATORS = [ { 'NAME': 'speedy.core.accounts.validators.PasswordMinLengthValidator', }, { 'NAME': 'speedy.core.accounts.validators.PasswordMaxLengthValidator', }, ] (which is defined in https://github.com/speedy-net/speedy-net/blob/uri_merge_with_master_2018-12-26_a/speedy/net/settings/global_settings.py). And then in the models, I tried to use: from django.conf import settings as django_settings class User(ValidateUserPasswordMixin, PermissionsMixin, Entity, AbstractBaseUser): settings = django_settings.UserSettings (and then use attributes of settings, such as settings.MIN_USERNAME_LENGTH, in the class). But it throws an exception AttributeError: 'Settings' object has no attribute 'UserSettings' (but it doesn't throw an exception if I use there a constant which is not a class). This is the first problem. In the meantime, I defined instead: from speedy.net.settings import global_settings … -
Django ORM annotation with tree traversal
I'm using the django-mptt library to make categories for my project. The model is pretty simple: from django.db import models from mptt.models import MPTTModel, TreeForeignKey class Category(MPTTModel): name = models.CharField('Name', max_length=100, unique=True) color = models.CharField( 'Color', max_length=100, blank=True, null=True ) parent = TreeForeignKey( 'self', on_delete=models.CASCADE, null=True, blank=True, related_name='children' ) class MPTTMeta: order_insertion_by = ['name'] Category color is optional and should be inherited from parent. So just to illustrate: Main Category 1 (red) -> Subcategory 1 -> Subcategory 2 (blue) -> Subcategory 3 (yellow) -> Subcategory 4 Subcategory 4 has no color defined and it inherits subcategory 3 color (yellow). Subcategory 1 inherits color from Main Category 1 (blue), etc. In my view i have the root category and then build a tree using get_descendants(include_self=True). How can i annotate color for each category of <TreeQuerySet>? For one model i have the following method: @property def inherited_color(self): if self.color: return self.color return (self .get_ancestors(ascending=True, include_self=True) .filter(color__isnull=False) .values_list('color', flat=True) .first()) But when this method is called for a list of categories it results in a lot of database queries! This is an example from django shell: >>> category <Category: 3> >>> category.color is None True >>> category.get_family().values_list('name', 'color') <TreeQuerySet [('1', '#51DCFF'), ('2', None), … -
How can I write my own permissions in django
I want to write my own permissions in Django, I mean I want to define exactly what a user can or cannot do, I have read this enter link description here but it seems change_task_status is sth predefined in Django. for example, I want to define exactly users can have access to just get method of a view and just from row 1 to 8 of the database table, and sth like this. How can I do this? -
Django | SuspiciousFileOperation error when creating a new profile object
I have an error when creating a new profile: SuspiciousFileOperation at /create_profil The joined path C:\Users\user\PycharmProjects\project\media\photo\2018\12\27\jhg.png) is located outside of the base path component (C:\Users\user\PycharmProjects\project\media\) These are my settings: STATIC_URL = '/static/' LOGIN_REDIRECT_URL = '/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/' print("---------------------------" + MEDIA_ROOT) STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn") This is my model: class Profil(models.Model): nom = models.CharField(max_length=120) image = models.ImageField(default='defaut.png', upload_to='image/%Y/%m/%d', blank=False, null=True) How can I get rid of this error? -
Django : Why POST urls are not working in Django AJAX?
I am creating a Like Button in Django using AJAX calls for my home page(where I have List of Posts which user can Like), For testing Logic of Like Button I had used normal(with page refresh) way to submit the form, and it works properly where I give URL as action='{% url "like_post" %}'. But when I went for AJAX based form submit I am Getting Error as POST http://127.0.0.1:8000/like/ 404 (Not Found). template.py: {% for post in all_posts %} <div class="posts" id="post-{{ post.id }}"> <h2 class="thought-title">{{ post.title }}</h2> <p class="content" id="{{ post.id }}" onclick="showWholeContent({{ post.id }})"> {{ post.content }} </p> <div class="post-footer"> <form id="like-form{{ post.id }}"> {% csrf_token %} <button type="submit" id="{{ post.id }}btn" name="like" value="{{ post.id }}" class="btn upvote">Like</button> <script type="text/javascript"> {% for like in post.likes.all %} {% if like != user %} {% else %} likingPost("{{ post.id }}btn"); {% endif %} {% endfor %} // Adding AJAX for Like button $(document).ready(function(event){ $(document).on('click', '#{{ post.id }}btn', function(event){ event.preventDefault(); $.ajax({ type: 'POST', url: '{% url "like_post" %}', data: { csrfmiddlewaretoken: '{{ csrf_token }}' }, success:function(response){ } }); }); }); </script> </form> </div> </div> {% endfor %} urls.py: urlpatterns = [ path('like/', views.like_post, name="like_post") . . . ] views.py: def … -
In Django, how to count the number of data in model and output in admin?
I am building a model by Django, similar to the below one. I will import the food data one by one like {supermarket_id, Fruit, apple}. At the end, I want to count how many food are in Fruit category and show it in the admin page. How can I achieve this? Besides, should I separate the category into a new class and make it as a ForeignKey? Many Thank. models.py class Food(BaseModel): CATEGORY_TYPE = ['Vegetable', 'Meat', 'Fruit'] #supermarket foreignkey contain the id supermarket = models.ForeignKey(SuperMarket, on_delete=models.CASCADE, verbose_name='supermarket', help_text='supermarket') category = models.CharField(max_length=64, choices=CATEGORY_TYPE, default=CATEGORY_TYPE[0][0], verbose_name="Food_Cetagory", help_text="Food_Category" ) food = models.CharField(max_length=128, default="NULL", verbose_name="Name", help_text="Name" ) class Meta: verbose_name = 'Food_Pyramid' verbose_name_plural = 'Food_Pyramid' def __str__(self): return '%s:%s' % (self.category, self.food) admin.py class FoodAdmin(admin.ModelAdmin): list_display = ("supermarket", "category", "food", "number") -
How to add resend interval to django activation emails?
I have set up my django backend to send the activation email (with activation link) to the user's email address provided at registration. But recently, I have been getting spam attacks where the user (or bot or whatever) requests the activation link continuously and increases the load on my email server. To counter this, how can I add a time delay/interval between successive requests for an activation email to the same email address? Should I create a custom view for this? if so, what view should I look at modifying and how can I add a time interval that say restricts the user from requesting 1 an activation link every 5 or 10 mins? -
Django Many-to-Many fields: Do they preserve ordering?
I am trying to represent the idea of a "workflow" in Django, but I'm a bit confused. For reference, this in the context of a CMS. Every Article object has a position in a given workflow. Every Workflow is an array of WorkflowItems, which contain two fields: a Section (News, Sports, Opinion) and a role within that section (contributor, editor, etc.) These workflows are created dynamically by users (i.e. there are no pre-defined workflows). For example, a given article can be in the writing stages with the journalist, or in the copy-editing stages. I originally tried representing this as an ArrayField (I am using a Postgres database), but Django threw an error saying Base field for array cannot be a related field. Section model: class Section(models.Model): name = models.CharField(max_length=32, null=False, blank=False) Workflow Item: class WorkflowItem(models.Model): section = models.ForeignKey(Section, null=True, on_delete=models.CASCADE) role = models.CharField( max_length=2, choices=ROLE_CHOICES, default=CONTRIBUTOR ) Workflow: class Workflow(models.Model): section = models.ForeignKey(Section, null=True, on_delete=models.SET_NULL) workflow = ArrayField(models.ForeignKey( WorkflowItem, null=True, on_delete=models.SET_NULL)) I need users to be able to move articles through workflows both forwards and backwards (i.e. order matters). -
How to pass title and name in render function
This is what I have in my view.py. I want to include title in my render function. def about(request): return render(request, 'blog/about.html', name='about') I have tried several options, including this; def about(request): return render(request, 'blog/about.html', {'name':'about','title': 'about'}) The above generates an error: NoReverseMatch at / Reverse for 'about' not found. 'about' is not a valid view function or pattern name. -
KeyError at /users/register/ 'password1'
i want to generate password for all users as test@123 but it is giving me error. Even i want to remove password input field from template Register.py def register(request): if request.method == 'POST': ur_form = UserRegisterForm(request.POST) pr_form = UserProfileForm(request.POST, request.FILES) # Getting User Role Id of Current Logged in Users user_role = 0 if request.user.userprofile.user_role_id == 1: # 1 for Super Admin user_role = 2 elif request.user.userprofile.user_role_id == 2: # 2 for Admin user_role = 3 elif request.user.userprofile.user_role_id == 3: # 3 for Manager user_role = 4 # 4 for Employee if ur_form.is_valid() and pr_form.is_valid(): new_user = ur_form.save(commit=False) new_user.username = new_user.email password = 'test@123' new_user.set_password(password) # <- here new_user.save() profile = pr_form.save(commit=False) if profile.user_id is None: profile.user_id = new_user.id profile.user_role_id = user_role profile.save() username = ur_form.cleaned_data.get('username') messages.success(request, 'Your Account has been created for %s!' % username) return redirect('users') else: ur_form = UserRegisterForm() pr_form = UserProfileForm() return render(request, 'users/register.html', {'ur_form': ur_form, 'pr_form': pr_form}) Forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField() first_name = forms.CharField() last_name = forms.CharField() class Meta: model = User fields = ['first_name','last_name', 'email', 'password1','password2'] def __init__(self, *args, **kwargs): super(UserRegisterForm, self).__init__(*args, **kwargs) del self.fields['password1'] del self.fields['password2'] -
Django Inlineformset: How to get access to parent's parent model?
I still can't get how to use InlineFormset well. What I want to do is like this. models.py class Questionarrie(models.Model): ... class Option(models.Model): questionarrie = models.ForeignKey(Questionarrie, on_delete=models.CASCADE) class Answer(models.Model): option = models.ForeignKey(Option, on_delete=models.CASCADE) user = models.ForeginKey(Customuser, on_delete=models.CASCADE) and views.py is like this # if the user already answered the question, get the answers that belong to the questionnaire and and the user answers = Answer.objects.filter(option__questionnaire=questionnaire, user=request.user) if not answers is None: formset = AnswerQuestionnaireFormset(instance=) and here I want to create formset based on answers (the answers that the user already answered in the past) but I don't get how to do this. Is it possible to create inlineformset based on multiple parents and getting access to parent's parent (in my case, getting access to Questionnaire)? -
How to update many related files from a model?
What should i do to get in the update view the files which correspond to the object to update? I've already make the CreateView to post the object Session with 20 files maximum, and it works, doesn't matter if is just 1 file or 10. But i don't know how to show the created files in the form for the UpdateView #-----------Models.py------------ class Session(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE ,verbose_name="usuario") front_image = models.ImageField(upload_to=upload_path_handler_front, null=True, blank=True, verbose_name='portada') title = models.CharField(max_length=128, verbose_name="titulo") description = models.TextField(null=True, blank=True,verbose_name="descripcion") date = models.DateField(default=now, verbose_name='fecha') class Meta: ordering = ['-date'] def __str__(self): return self.title class Images(models.Model): session = models.ForeignKey(Session, default=None, on_delete=models.CASCADE) image = models.ImageField(upload_to=upload_path_handler, null=True, blank=True, verbose_name='imagen') class Meta: verbose_name="image" verbose_name_plural="images" def __str__(self): return str( self.session ) #-----------views.py------------------- @login_required def session(request): ImageFormSet = modelformset_factory(Images, form=ImageForm, extra=20) if request.method == 'POST': sessionForm = SessionForm(request.POST, request.FILES) formset = ImageFormSet(request.POST, request.FILES, queryset=Images.objects.none()) if sessionForm.is_valid() and formset.is_valid(): session_form = sessionForm.save(commit=False) session_form.user = request.user session_form.save() for form in formset.cleaned_data: if form: image = form['image'] photo = Images(session=session_form, image=image) photo.save() messages.success(request, "Created") return HttpResponseRedirect(reverse_lazy('List-session-admin')) else: print(sessionForm.errors, formset.errors) else: sessionForm = SessionForm() formset = ImageFormSet(queryset=Images.objects.none()) return render(request, 'session/crud/create_session.html', {'sessionForm': sessionForm, 'formset': formset}) class Update_Session(generic.UpdateView): template_name = 'session/crud/update_session.html' model = Session form_class = UpdateSessionForm success_url = … -
how to exclude model form validation from admin
I need if a user does not select the field acc_type, the user will not proceed to registration. So I have written in model blank=False. But the problem is when superuser updates his information after login, user form holds superuser to fill that field. So, I want validation for some fields should be excluded for superuser, stuff or admin type users. Please see the screenshot: What I did in model: models.py class Ext_User(AbstractUser): email = models.EmailField(unique=True) ACC_TYPE = ( (1, "Member"), (2, "Vendor") ) acc_type = models.IntegerField("Account Type", choices=ACC_TYPE, null=True, blank=False) -
Translation with context in Django - makemessages doesn't recognize our context
We are using Django for Speedy Net and Speedy Match (currently Django 1.11.17, we can't upgrade to a newer version of Django because of one of our requirements, django-modeltranslation). I have a problem with translating strings with context. We use context mainly for translating strings differently depending on the user's gender, which translates differently in languages such as Hebrew, although the English strings are the same. For example, I have this code: raise ValidationError(pgettext_lazy(context=self.instance.get_gender(), message="You can't change your username.")) (you can see it on https://github.com/speedy-net/speedy-net/blob/uri_merge_with_master_2018-12-26_a/speedy/core/accounts/forms.py) The problem is that manage.py makemessages doesn't recognize the context here. A workaround we found is to include this text manually in files we don't use at all, such as __translations.py or __translations.html (you can see them on https://github.com/speedy-net/speedy-net/blob/uri_merge_with_master_2018-12-26_a/speedy/core/base/__translations.py and https://github.com/speedy-net/speedy-net/blob/uri_merge_with_master_2018-12-26_a/speedy/core/templates/__translations.html respectively), and there we can include the same strings with context: Either: pgettext_lazy(context="female", message='Your new password has been saved.') pgettext_lazy(context="male", message='Your new password has been saved.') pgettext_lazy(context="other", message='Your new password has been saved.') Or: {% trans "You can't change your username." context 'female' %} {% trans "You can't change your username." context 'male' %} {% trans "You can't change your username." context 'other' %} But this is a lot of work and we have … -
TemplateDoesNotExist at / index.html - URL Dispatcher Issues in Django
Attempting to create a simple application using Django 2.1.4. Project name is "inventory_management", application inside the project is called "gInventory". Here is tree view of my file management: | db.sqlite3 | manage.py | tree.txt | +---gInventory | | admin.py | | apps.py | | models.py | | tests.py | | urls.py | | views.py | | __init__.py | | | +---migrations | | __init__.py | | | +---static | | +---css | | | bootstrap-grid.css | | | bootstrap-grid.css.map | | | bootstrap-grid.min.css | | | bootstrap-grid.min.css.map | | | bootstrap-reboot.css | | | bootstrap-reboot.css.map | | | bootstrap-reboot.min.css | | | bootstrap-reboot.min.css.map | | | bootstrap.css | | | bootstrap.css.map | | | bootstrap.min.css | | | bootstrap.min.css.map | | | style.css | | | | | \---js | | bootstrap.bundle.js | | bootstrap.bundle.js.map | | bootstrap.bundle.min.js | | bootstrap.bundle.min.js.map | | bootstrap.js | | bootstrap.js.map | | bootstrap.min.js | | bootstrap.min.js.map | | | +---templates | | base.html | | index.html | | | \---__pycache__ | urls.cpython-37.pyc | views.cpython-37.pyc | __init__.cpython-37.pyc | \---inventory_management | settings.py | urls.py | wsgi.py | __init__.py | \---__pycache__ settings.cpython-37.pyc urls.cpython-37.pyc wsgi.cpython-37.pyc __init__.cpython-37.pyc Whenever I run my local server and try and pull up … -
migrate from tastypie to DRF
I'm working on django-tastypie project and I want to migrate to django rest framework. I need an article or a document or anything else that help me to this. for example this document bring a sample of both framework and evaluate them. I search all of the same document but I don't find helpful doc! -
Manual Password with hiding password field Django
i am using User in-built model of django. I want to create password for user like 'test@123' for everyone. without showing password field in template register.py @login_required def register(request): if request.method == 'POST': ur_form = UserRegisterForm(request.POST) pr_form = UserProfileForm(request.POST, request.FILES) if ur_form.is_valid() and pr_form.is_valid(): new_user = ur_form.save(commit=False new_user.username = new_user.email password = 'test@123' new_user.password = password new_user.save() profile = pr_form.save(commit=False) if profile.user_id is None: profile.user_id = new_user.id profile.user_role_id = 3 profile.save() username = ur_form.cleaned_data.get('username') messages.success(request, 'Your Account has been created for %s!' % username) return redirect('users') else: ur_form = UserRegisterForm() pr_form = UserProfileForm() return render(request, 'users/register.html', {'ur_form': ur_form, 'pr_form': pr_form}) Forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField() first_name = forms.CharField() last_name = forms.CharField() class Meta: model = User fields = ['first_name','last_name', 'email'] def __init__(self, *args, **kwargs): super(UserRegisterForm, self).__init__(*args, **kwargs) del self.fields['password1'] del self.fields['password2'] -
Building URL from name
I've got a url of 'accounts:produce_setup' (i.e. namespace/app is 'accounts' and name of url is 'product_setup'). I'd like to build the full url associated with this view and pass it as context into a template. How would I go about doing this? Would I use build_absolute_uri()? Thanks! -
Django: use form to assign a set of permissions to a group, permission based on queryset of users
Looking for advice on how to handle this: App will have a number of privileged views that only certain community manager users will be able to access (these are not admin users). I want to be able to have a form where the one manager user can create a group with a specific set of permissions (check boxes out of the list of all possible permissions), and certain managers can be assigned to given groups. ie. Manager 2 is in Group 2 and can access the "deactivate" and "reactivate" views but Manager 3 is in Group 3 and can only access the "reactivate views." Let's say I have Users and Hotel models. The permissions may need to be fine-grained; ie. Manager 2 (or Group 2) can only access Users from the same Organization or possibly from a specific department within the Organization. Manager 3 can access users from one specific department, or can only access the "deactivate view" for Hotel.objects.filter(country="France"). So it's not just giving a manager a certain permission to view an object ie. not just assign permission for a specific object, it's permissions to view all objects that have certain attributes. The permission would be ("permission to access … -
Issue importing model for a different app withing the same django project
I have a django project with two different apps in it. There is a users and campaign app. I am working with the campaign models and I want to import a users model to link as a foreign key. I can successfully import a campaign model into the users model and set it as foriegn key. I cant do it the other way around. I will be attaching some peices of code below. THE IMPORT STATEMENTS - campaign models python file: from django.db import models from users.models import Founder from .choices import CATEGORY_CHOICES, PLATFORM_CHOICES, PROGRESS_CHOICES, SIZE_CHOICES the campaing model that needs access to the users model being imported: class Update(models.Model): campaign = models.ForeignKey(Detail, on_delete=models.CASCADE) message = models.TextField() impact = models.TextField() founder = models.ForeignKey(Founder, on_delete=models.CASCADE) def __str__(self): return self.campaign.name + ' update' This is the model I am trying to import: class Founder(models.Model): user = models.ForeignKey(Credential, on_delete=models.CASCADE) campaign = models.ForeignKey(Detail, on_delete=models.CASCADE) company = models.CharField(max_length=50) position = models.CharField(max_length=30) commitment = models.TextField(null=True) since_month = models.CharField(max_length=15, choices=MONTH_CHOICES) since_year = models.IntegerField() portfolio = models.CharField(max_length=200) relation = models.TextField() known = models.IntegerField() verified = models.BooleanField(default=False) def __str__(self): return self.user.username + '-' + self.campaign.name Here is the file structure I have setup right now. -
How do I delete the previous saved image and save the new one without duplicating? Django
I'm having trouble saving image. My Model is this class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pic') def __str__(self): return f'{self.user.username} Profile' def save(self, **kwargs): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) This model has and OneToOne relation field with the default user model and an image field. I am overriding the save() method to rezize the image. But When I'm saving image with this model, It's saved with and automatic unique name. See the image below, Screenshot of file system But I want to save image like this.. If user uploads an image, it'll delete the previous image of the user and it'll save the new image with an unique name. How do I do it? -
How to run multiple root domains/subdomains off single django heroku app?
Have been researching this and found some old suggestions, but I'm wondering if anyone who is actually doing the above could advise on the best way to accomplish this (and if it is advisable?) I want to white-label an app to different customers but would like to be able to point multiple root domains or subdomains to a single heroku app to save costs. Has anyone done this? The views, templates, model structure are the same for each organization, but Users/Organizations belong to a given domain. I want to make sure example1.com customers can only access example1.com/ and example2.com customers can access example2.com/. The sites framework suggests that setting SITE_ID=None means I can still query the current site since it uses get_host(). But if I do this, I can't set individual settings files like the normal sites framework. Is it certain that request.site is accurate and will it be easy to do things like reverse() to the correct url and send emails where the FROM email is from the correct site. I could do something like save the site domain on organization and check in views: if request.user.organization.domain == request.site: Would appreciate any advice on packages to use (would django-tenant-schemas … -
How to provide conditions in manytomany fields?
I have a django admin page, where I can add services and map then in 3 types of labs( Professional, Innovation and partner). Then I create the labs, there I give the lab-type and select the services while creating. What I am can't figure out is, if I am going to create a Professional lab, lab should be created only if I select the services which are mapped in Professional Lab. I have added the model code and snaps below. Lab creation page, we have a save button which is not seen here Service creation page [ Services are created using this function class Service(models.Model): name = models.CharField(max_length=50) fullname = models.CharField(max_length=100) cloud = models.CharField(max_length=10, default='aws') __Here the services are mapped to labs using check-boxes__ in_professional = models.BooleanField(default=False) in_innovation = models.BooleanField(default=False) in_partner = models.BooleanField(default=False) def save(self, *args, **kwargs): self.name = self.name.lower() self.fullname = self.fullname.title() self.cloud = self.cloud.lower() super(Service, self).save(*args, **kwargs) def __str__(self): return self.name Labs are created in this function class Lab(models.Model): class Meta: unique_together = (('name', 'cloud'),) name = models.CharField(max_length=100) __The input for lab type is given here__ type = models.CharField(max_length=100, default='professional') # 'professional' | 'innovation' | 'partner' cloud = models.CharField(max_length=25, default='aws') budget_allocated = models.IntegerField(default=1) budget_spent = models.IntegerField(default=0) configuration = … -
usage: py [-x] [-l] [-c PRE_CMD] [-C POST_CMD] [-V] [-h] [expression]
i get this error when ever i do anything I just installed Ubuntu and now i cant run any of my django project. is it some problem with my python/django version ?