Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django rest framework: Get nested representation of child elements
I have a tree of items which reference each other as parent/children. Now I want to get them through the API as nested objects to minimize the requests. My problem is that I can't initiate the serializer class from within itself (obviously)... Is there a way to do this? Model: class Item(models.Model): name = models.CharField(max_length=128) dashboard = models.ForeignKey(Dashboard, on_delete=models.CASCADE) config = models.JSONField(null=True, blank=True) parent = models.ForeignKey("Item", on_delete=models.CASCADE, related_name="children", null=True, blank=True) previous = models.OneToOneField("Item", related_name="next", null=True, blank=True, on_delete=link_previous_item_on_delete) Serializer: class ItemSerializer(serializers.HyperlinkedModelSerializer): children = ItemSerializer(many=True, read_only=True) class Meta: model = Item fields = ("name", "dashboard", "config", "children") -
Is there a way to use a temporary non-field variable in factoryboy?
I am defining some factories for testing my e-commerce store. I have created a Faker provider that can return, for instance, a dictionary containing all the data for a random product. I want to then use that dictionary to populate the fields in my factory. This is because the data in the dictionary is coherent. I don't want to create a factory with data that is not coherent e.g. a Product with name: "Short sleeve t-shirt" and then description: "Beautiful, comfortable shoes." Is there a way that I can implement something similar to class ProductFactory(factory.django.DjangoModelFactory): temporary_product_dict = fake.product_dict_from_provider() name = temporary_product_dict["name"] description = temporary_product_dict["description"] category = temporary_product_dict["category"] ... class Meta: model = models.Product When I do this exact thing, I get an error which tells me that temporary_product_dict is not an attribute of the Product model. -
Load values from Models.py into Views.py
I am trying to create a page that allows a user to change certain CSS variables in the Django admin page and I am having some issues pulling a single value from the models.py and assigning it to a variable in my views.py. Assigning the colors inside the Django admin page works but I am unsure of how I would go about setting the linkcolor variable in views.py to the link_color variable in models.py. views.py from django.shortcuts import render from django.http import HttpResponse from .models import cssEditor # Create your views here. def index(request): linkcolor = "#000" # Grab link_color from models.py here linkfont = "Brush Script MT" # Grab link_font from models.py here linkbc = "whitesmoke" # Grab link_bc from models.py here return render(request, "SocialLinks/index.html", {"linkcolor":linkcolor, "linkfont":linkfont, "linkbc":linkbc}) models.py from django.db import models # Create your models here. class cssEditor(models.Model): link_color = models.CharField(max_length=7, default="000000") link_font = models.CharField(max_length=15, default="Brush Script MT") link_bc = = models.CharField(max_length=7, default="#F5F5F5") admin.py from django.contrib import admin from SocialLinks.forms import * # Register your models here. @admin.register(cssEditor) class cssEditor(admin.ModelAdmin): form = cssForm forms.py from django.forms import ModelForm from django.forms.widgets import TextInput from SocialLinks.models import * class cssForm(ModelForm): class Meta: model = cssEditor fields = "__all__" widgets … -
how to auto set the topic of a comment to the same topic with the post
i want to be able to create comments by clicking on the comment link under the post, every post has a topic, but i'm unable to get the comments under a specific post, so i thought to add the topic as well for more functionality, but i'm finding it hard to automatically assign the topic based on what post i'm commenting on my views.py the pk is set as the post.id def comment(request, pk): form = commentform() context = { 'form' : form } if request.method == 'POST': form = commentform(request.POST) if form.is_valid(): forms = form.save(commit=False) forms.posts = post.objects.get(id=pk) forms.owner = request.user forms.topics = topic.objects.get(id=pk) forms.save() return redirect('home') return render(request, 'base/comment.html', context) my models.py class comments(models.Model): topics = models.ForeignKey(topic, on_delete=models.CASCADE, SET_NULL=True, null=True) created = models.DateTimeField(auto_now=True) posts = models.ForeignKey(post, on_delete=models.CASCADE) owner = models.ForeignKey(User, on_delete=CASCADE) comment = models.TextField(max_length= 500) def __str__(self): return str(self.comment) class post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) Topic = models.ForeignKey(topic, on_delete=models.CASCADE) post = models.TextField(max_length=500) created = models.DateTimeField(auto_now=True) def __str__(self): return f'{self.post}' my forms.py class commentform(ModelForm): class Meta: model = comments fields = ['comment'] -
Django.db.utils.DataError: invalid input syntax for type integer: "Build"
I have thee model class, with manytomany field, and i use postegresql as base, problem is when I migrate my models terminal shows : how can i fi it ? File "C:\Users\zura\Desktop\personalization\manage.py", line 21, in <module> main() File "C:\Users\zura\Desktop\personalization\manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\zura\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\management_init_.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\zura\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\management_init_.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\zura\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) django.db.utils.DataError: invalid input syntax for type integer: "Build" class Person(models.Model): name = models.CharField(max_length=50, null=True) def __str__(self): return self.fullname class Features(models.Model): name = models.CharField(max_length=30, null=True) feature = models.ManyToManyField(Person, through='Enrollment') def __str__(self): return self.name class Enrollment(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE, null=True) job = models.ForeignKey(Features, on_delete=models.CASCADE, null=True) def __str__(self): return self.person.fullname -
Set a limit of submits forms with the same object
I'm working on a school project where there are activities with different limits of people they can have plaatsen_beschikbaar. Also, students can only apply for one activity beperk_aanmelden. models.py class Activiteit(models.Model): titel = models.CharField(max_length=64) docent = models.CharField(max_length=32) icon = models.ImageField() uitleg = models.TextField() plaatsen_beschikbaar = models.IntegerField() def beperk_aanmelden(value): if Aanmelden.objects.filter(studentnummer=value).count() >= 1: raise ValidationError('Student heeft al de maximale aanmeldingen') else: return value class Aanmelden(models.Model): naam = models.CharField(max_length=32) studentnummer = models.IntegerField(validators=[beperk_aanmelden,]) klas = models.ForeignKey(Klas, on_delete=models.CASCADE, default=None, blank=True) activiteit = ForeignKey(Activiteit, on_delete=models.CASCADE, default=None, blank=True) Aanmelden is the model to apply to an activity. views.py def home(request): activiteiten = Activiteit.objects.all() form = AanmeldenForm() if request.method == 'POST': form = AanmeldenForm(request.POST) if form.is_valid(): form.save() Aanmelden.objects.get() return render(request, 'home.html', { 'activiteiten': activiteiten, 'form':form, }) I need to do a function that discounts the available places in an activity and when it reaches 0 it doesn't allow any more submits to that activity. It's literally the last function from my backend I have to do to finish this and it's gotta be done by monday so how can I do this? -
Proper way to use clean_email in DRF
I've defined the model as pass and I'm using the UserSerializer to validate the password and create a new user. What I'm trying to do is that people can only SignUp if it's not with a known provider such gmail.com, outlook.com, live.com, etc. I know in DJango there is the clean_emailfeature that would help with something like this: class SignUpForm(forms.ModelForm): class Meta: model = SignUp fields = ['username', 'email'] def clean_email(self): email = self.cleaned_data.get('email') email_base, provider = email.split("@") domain, extension = provider.split('.') Is there any similar functionality in Django Rest Framework? I've looked up but couln't find anything -
Django response - if POST = None leave blank key, value pair from jsonresponse
the below form + view works fine forms.py class FormGlobalSettings(forms.Form): global_font_family = forms.TypedChoiceField(required=False, label='Font Family', choices=choices_font_family, empty_value=None) views.py def main_view(request): if request.method != 'POST': form_global_settings = FormGlobalSettings() else: form_global_settings = FormGlobalSettings(data=request.POST) if all([form_global_settings.is_valid()]): cleaned_data = form_global_settings.cleaned_data nested_data = {"fontFamily": cleaned_data3['global_font_family']} return JsonResponse(nested_data) return render(request, 'pbi_theme_app/index.html', {'form_global_settings': form_global_settings}) Output is: {"fontFamily": "Arial"} However, what I am trying to achieve is, that sometimes the POST request is blank/empty/null, as the user doesn't want to have any value in this field. The choices for the global_font_family are set up in this manner: choices_font_family = [(None, ""), ("Arial", "Arial"), etc..] Meaning that the if the user leaves the field empty, it results into None. This results into having it in the json as null: {"fontFamily": null} Now what I am trying to achieve, and because I have hardcoded "fontFamily" into the jsonresponse, I want the whole key, value pair to be gone if the user decides to have the field empty, meaning that the whole key, value pair "fontFamily: null is gone from the jsonresponse. To summarize: I need to somehow make the key in the json dynamic, and when the POST request is empty, I want to leave the whole key, value pair … -
Django ModuleNotFoundError: No Module named 'localflavor'
I am getting a perplexing ModuleNotFound error with a project where I am attempting to start a new app. This has not been a problem until just now. When I run: python manage.py startapp newapp I get the following error: Traceback (most recent call last): File "/Users/mainuser/Desktop/ohive/manage.py", line 22, in <module> main() File "/Users/mainuser/Desktop/ohive/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/mainuser/.local/share/virtualenvs/ohive-ogMUOXTX/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Users/mainuser/.local/share/virtualenvs/ohive-ogMUOXTX/lib/python3.9/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/Users/mainuser/.local/share/virtualenvs/ohive-ogMUOXTX/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/mainuser/.local/share/virtualenvs/ohive-ogMUOXTX/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Users/mainuser/.local/share/virtualenvs/ohive-ogMUOXTX/lib/python3.9/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/Users/mainuser/.pyenv/versions/3.9.2/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'localflavor' (ohive) bash-3.2$ python manage.py startapp tenant_howto /tenant_customapps/intranet Traceback (most recent call last): File "/Users/mainuser/Desktop/ohive/manage.py", line 22, in <module> main() File "/Users/mainuser/Desktop/ohive/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/mainuser/.local/share/virtualenvs/ohive-ogMUOXTX/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Users/mainuser/.local/share/virtualenvs/ohive-ogMUOXTX/lib/python3.9/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/Users/mainuser/.local/share/virtualenvs/ohive-ogMUOXTX/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/mainuser/.local/share/virtualenvs/ohive-ogMUOXTX/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Users/mainuser/.local/share/virtualenvs/ohive-ogMUOXTX/lib/python3.9/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File … -
No module named 'social_django' but 'social-auth-app-django' is installed
Summary of Issue I am creating a Django project and attempting to setup Auth0 integrations. Per Auth0's documentation, I installed the social-auth-app-django library which then went and also installed social-auth-core. So please note that both these libraries are installed. Here is my py -m pip list output proving such: Package Version ---------------------- --------- asgiref 3.4.1 certifi 2021.10.8 cffi 1.15.0 charset-normalizer 2.0.7 colorama 0.4.4 cryptography 35.0.0 defusedxml 0.7.1 Django 3.2.9 ecdsa 0.17.0 idna 3.3 oauthlib 3.1.1 pip 21.3.1 pyasn1 0.4.8 pycparser 2.21 PyJWT 2.3.0 python-dotenv 0.19.2 python-jose 3.3.0 python-social-auth 0.3.6 python3-openid 3.2.0 pytz 2021.3 requests 2.26.0 requests-oauthlib 1.3.0 rsa 4.7.2 setuptools 57.4.0 six 1.16.0 social-auth-app-django 5.0.0 social-auth-core 4.1.0 sqlparse 0.4.2 urllib3 1.26.7 As you can see, I'm running Django 3.2.9. I am also using Python 3.10. After following all of Auth0's steps, I went to run py manage.py migrate and receive the following ending error message: ModuleNotFoundError: No module named 'social_django' What I have tried I have tried uninstalling and reinstalling the social-auth-app-django and social-auth-core libraries multiple times. I have also tried installing the libraries individually instead of just installing social-auth-app-django. I have also tried installing social-auth-app[django] (using brackets). Nothing has worked. Every post I can find online is telling the … -
Django field DateField with year only or with year and month etc. with filtering
I have a question regarding the DateField. Is there any possibility for the field to accept only a year or a year and a month? I want to add an incomplete date to the database and filter by this field. I download books from API and the date is not always full there. I want to download the results, save them to the database and display a list of these objects on the page with an incomplete date or a complete date. -
Django - constructing multi column indexes
Say we have a model that looks thus: class Entry(models.Model): """Users will query for entries with various combinations of filters""" date_created = models.DateTimeField(auto_now_add=True) important = models.BooleanField(default=False, null=False) urgent = models.BooleanField(default=False, null=False) user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) What is the correct way to create indexes that will cater for any combination of the above fields in filters? E.g. .filter(date_created__year='2021', important=False, user=1) My first thought was the below but I have a suspicion I'm doing something wrong here... class Meta: indexes = [models.Index(fields=['-date_created']), models.Index(fields=['-date_created', 'important']), models.Index(fields=['-date_created', 'important', 'urgent']), models.Index(fields=['-date_created', 'important', 'urgent', 'user']), models.Index(fields=['-date_created', 'user']), models.Index(fields=['....etc...'])] I read through the Django documentation and noted their use of the include argument that was introduced in Django 3.2, but was unable to find useful examples of it's use. Would it work in my situation? class Meta: indexes = [models.Index(fields=['-date_created'], include=['important', 'urgent', 'user'])] Thank you -
get list of items, which were passed from python file (Django) to html, from html to Javascript, which is on the same page
my python code: def index(request): body=list(Body.objects.all()) loads=list(Load.objects.all().order_by('length')) badLoads=[] goodLoads=[] for load in loads: if load.length>body[0].length or load.width>body[0].width or load.mass>body[0].mass: badLoads.append(load) else: goodLoads.append(load) goodLoadsLength=len(goodLoads) context={ 'body':body[0], 'loads':loads, 'badLoads':badLoads, 'goodLoads':goodLoads, 'goodLoadsLength':goodLoadsLength, } return render(request,'index.html',context) html code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Positioning of objects</title> </head> <body> <div> {% if body %} <p>body length: {{ body.length }}, body width: {{ body.width }}, body height: {{ body.height }}, body max mass, which can be taken: {{ body.mass }}</p> {% else %} <p>No parameters found</p> {% endif %} </div> <div> {% if loads %} <ul> {% for load in loads %} <li>load id: {{ load.id }}, load length:{{ load.length }}, load width: {{load.width}}, load height: {{load.height}}, load mass: {{load.mass}}</li> {% endfor %} </ul> {% else %} <p>No loads are available.</p> {% endif %} </div> <div> {% if goodLoads %} <ul> {% for goodLoad in goodLoads %} <li>load id: {{ goodLoad.id }}, load length:{{ goodLoad.length }}, load width: {{goodLoad.width}}, load height: {{goodLoad.height}}, load mass: {{goodLoad.mass}}</li> {% endfor %} </ul> {% else %} <p>No loads are available.</p> {% endif %} </div> <div> {% if loads %} <ul> {% for badLoad in badLoads %} <li>load id: {{ badLoad.id }}, … -
(Django) include does not import other apps' urls
In my Django project I have 2 apps: core and books. In my core/urls.py, I use python include('books.url') to import the urls from books/urls.py, but I keep getting this error I have been having this issue now that's bugging me. I had a workaround for it, though I really want to fix this. core/urls.py from django.contrib import admin from django.urls import path from django.conf.urls import include # local urlpatterns = [ path('/', include('books.urls')), path('admin/', admin.site.urls), ] books/urls.py from django.contrib import admin from django.urls import path # local from graphene_django.views import GraphQLView from books.schema import schema urlpatterns = [ path('graphql/', GraphQLView.as_view(graphiql=True, schema=schema)), ] As suggested by SO, I have: put books.urls inside the single quotes ' ' placed the path('/', include('books.urls')) on top switch from from django.urls import include to from django.conf.urls import include The only workaround I have is place all urls into the core/urls.py, but that seems too chunky in the long run. I don't get why include works for everyone but not me! Could you help me with this issue? Thank you! -
Django POST data to via form and redirect to page with POST data
I have a Django form, that once the data has been submitted I'd like to redirect to another page where the data will be displayed. I'm having trouble as I don't know how to retrieve the Foreign Key until the form has been submitted Form class addEventForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(addEventForm, self).__init__(*args, **kwargs) class Meta: model = Event fields = '__all__' View class addEventView(LoginRequiredMixin,View): template_name = 'pages/add_event.html' def get(self, request, *args, **kwargs): return render(request, self.template_name) def post(self, request, *args, **kwargs): form = addEventForm(request.POST) if form.is_valid(): form.save() data = {"success": "successfully added"} else: data = {"error": form.errors} return JsonResponse(data, safe=False) How do I redirect but pull in the data from the POST? Thanks -
Multiple forms with bootstrap modal in one single create view in Django
I have 5 forms: MyForm, EducationForm, ExperienceForm, RecommendationForm, OtherDocumentsForm. 1st is Main form and others (EducationForm, ExperienceForm,RecommendationForm,OtherDocumentsForm) should be in bootstrap modal. During filling the main form(MyForm), I also have to fill other forms with bootstrap modal and Finally all of them should be attached to Main form. I connected them other forms with Foreign key to MyForm. I stucked in this situation. Could anyone knows how to get data from bootstrap and connect them in one view? MyForms class MyForm(forms.ModelForm): class Meta: model = UserForm_uz fields = 'all' class EducationForm(forms.ModelForm): class Meta: model = Education_uz fields = 'all' class ExperienceForm(forms.ModelForm): class Meta: model = Experience_uz fields = 'all' class RecommendationForm(forms.ModelForm): class Meta: model = Recommendation_uz fields = 'all' class OtherDocumentsForm(forms.ModelForm): class Meta: model = OtherDocuments fields = 'all' My models: # Create your models here. language_choices = [('1', 'Билмайман'), ('2', 'Ёмон'), ('3', 'Лугат ёрдамида'), ('4', 'Ўртача'), ('5', 'Яхши'), ('6', 'Жуда яхши'), ] approve_choices = [('Yes', 'Ха'), ('No', 'Йўк')] agreement_choices = [('Yes', 'Ха'), ('No', 'Йўк')] class UserForm_uz(models.Model): rasm = models.ImageField(upload_to='rasmlar',null=True,blank=True) lastName = models.CharField(max_length=200) firstName = models.CharField(max_length=200) middleName = models.CharField(max_length=200) birthData = models.DateField() nation = models.CharField(max_length=50) birthPlace = models.CharField(max_length=250) marriage_status = models.CharField(max_length=20) children = models.CharField(max_length=20) militaryResp = models.CharField(max_length=150) language_uzbek = models.CharField(choices=language_choices,max_length=150) … -
How to get data from User related model to template
I have Profile model in addition to native User model. Since user is logged in, I need to load avatar image to all pages in frontend. I need something like this: {% if request.user.is_authenticated %}<img src={{ profile.avatar }}>{% endif %} How I can do that? class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(upload_to='media/avatar/', verbose_name='Аватар', default='media/avatar/default_avatar.jpg') @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() -
Setting a lazy reference to a django serializer class
I have two models which has a field reference to each other. Both were in seperate files, but i decided to put them in a single file to avoid circular import bugs. However, unlike making a lazy reference to a django model class, i can't seem to make it work here class QuestionAnsweringModelResultsSerializer(ModelSerializer): answers = AnswerAnsweringModelResultsSerializer(many=True) images = QuestionAnsweringModelImagesResultsSerializer(many=True) written_answer_marking_settings = QuestionMarkingSettingsSerializer() parent_question = QuestionResultsSerializer() procedural_answers = ProceduralAnswerAnsweringSerializer(many=True) # the field below makes reference to the class below fill_in_the_blanks_answers = FillInTheBlanksAnsweringModelResultsSerializer(many=True) class Meta: model = QuestionAnsweringModel fields = '__all__' class FillInTheBlanksAnsweringModelResultsSerializer(ModelSerializer): # the field below makes reference to the class above question = QuestionAnsweringModelResultsSerializer() class Meta: model = FillInTheBlanksAnsweringModel fields = '__all__' I get the error a class is not defined error where class is the name of the Serializer Class -
Django importing a custom user model
I have a Django app with a custom user model. I am attempting to import this model into another app. So far I can't figure out how to do this. The customer user model at accounts/models.py is from django.db import models from machina.core.db.models import get_model from django.db.models import Q from django.contrib.auth.models import Group # signals imports from django.dispatch import receiver from django.db.models.signals import ( post_save ) Forum = get_model("forum", "Forum") class CustomUser(AbstractUser): first_name = models.CharField(max_length=250, null=True) last_name = models.CharField(max_length=250, null=True) age = models.PositiveIntegerField(null=True, blank=True) business_name = models.CharField(max_length=250, null=True) business_location_state = models.ForeignKey( Forum, null=True, on_delete=models.SET_NULL, limit_choices_to={"lft": 1}) business_location_county = models.ForeignKey( Forum, null=True, on_delete=models.SET_NULL, related_name='county') business_location_city = models.CharField(max_length=1024, null=True) business_zipcode = models.CharField(max_length=12, null=True) The code I most recently tried to import this model is: from django.db import models from django.contrib.auth.models import User from django_tenants.models import DomainMixin, TenantMixin from django.utils.translation import ugettext as _ from localflavor.us.models import USStateField from accounts.models import CustomUser class Tenant(TenantMixin): user = models.ForeignKey('CustomUser', on_delete=models.SET_NULL, null=True) company_name = models.CharField(max_length=100) address_1 = models.CharField(_("address"), max_length=128) address_2 = models.CharField(_("address cont'd"), max_length=128, blank=True) city = models.CharField(_("city"), max_length=64) state = USStateField(_("state")) zip_code = models.CharField(_("zip code"), max_length=5) created_on = models.DateField(auto_now_add=True) When I attempt to start the server I get this error: django.core.management.base.SystemCheckError: SystemCheckError: System check identified … -
AWS EB CLI deployment Dango - Static files showing for web app but not showing for Admin panel
I have recently managed to setup and deploy my Django web app to AWS via EB CLI, everything looks fine on the web app however when I visit the admin panel I noticed the static files are not loading at all (but load fine on local server). I see on the S3 bucket admin static files were uploaded in the following structure (my app is called wfi_workflow): .elasticbeanstalk admin/ css/ fonts/ img/ js/ resources/ wfi_workflow/ Please see following relevant code in my project for static files: Settings BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR,'static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'assets') .ebextensions/django.config container_commands: 01_sh_executable: command: find .platform/hooks/ -type f -iname "*.sh" -exec chmod +x {} \; option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: wfi_workflow.settings aws:elasticbeanstalk:environment:proxy:staticfiles: /static: static /static_files: static_files aws:elasticbeanstalk:container:python: WSGIPath: wfi_workflow.wsgi:application .ebextensions/packages.config packages: yum: python3-devel: [] mariadb-devel: [] .platform/hooks/predeploy/01_migrations.ssh #!/bin/bash source /var/app/venv/*/bin/activate cd /var/app/staging python manage.py makemigrations python manage.py migrate python manage.py createsuperuser python manage.py collectstatic --noinput Help is much appreciated on this, Thanks. -
Field 'maca2' expected a number but got 'Select'
class Maca(models.Model): class Maca2(models.IntegerChoices): Personal = 1, Work = 2, Transport = 3, __empty__ = _('Select') When I submit as empty value I got the following error Field 'maca2' expected a number but got 'Select'. -
@login_required decorator is not working (Django)
I am trying to build a social media like thing and have created the login and signup feature. For home page I have added login_required decorator and even added LOGIN_URL in settings.py but still I am able to access the home page without login i.e login_required decorator is not doing its job. Here is my view function code @login_required def home(request): return render(request, 'home/home.html') Here is my code in settings.py LOGIN_URL = '/login' Can anyone find out what might be the problem? -
Create and Retrive django session objects
I have customised the django default user table and used it for user signup and login. Now I need to create django session object to create a shopping cart (like that of an ecommerce website) which is user specific.How to create and retrive session objects in django?? -
related_name in many to many field
Below is my code. class Thing(models.Model) : title = models.CharField( max_length=200, validators=[MinLengthValidator(2, "Title must be greater than 2 characters")] ) text = models.TextField() owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='fav_thing_owner') favorites = models.ManyToManyField(settings.AUTH_USER_MODEL, through='Fav', related_name='favorite_things') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) # Shows up in the admin list def __str__(self): return self.title class Fav(models.Model) : thing = models.ForeignKey(Thing, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='favs_users') # https://docs.djangoproject.com/en/3.0/ref/models/options/#unique-together class Meta: unique_together = ('thing', 'user') def __str__(self) : return '%s likes %s'%(self.user.username, self.thing.title[:10]) But I got confused related_name in ManytoMayFied. for example, in my code I can get user's Thing(my model name) using user.fav_thing_owner. But in ManyToManyField, I have two related_name(favorite_things, favs_users). user.favorite_things and user.favs_users get same object..? -
python single and multiple button operation
I have a concern on how to stimulate single or multiple button click operations. --code sample : .js file jQuery.ajax({ url : "/", type :"POST", data : { selected_obj : clicked_btn }) .py file object_selected = request.forms.get('selected_obj') # This (object_selected) return data like # data_returned = (0.48, 0.65, 2.32) -what i need is when the button clicked for the first time data_returned gets multiplied which it is no big deal. But when clicked for the second time either same or another button that has same output i need to (multiply the returned data) for the same or another button and sum it with the previous data(button clicked for the first time), and so on ..