Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I access user in Django Async view?
I'm trying to access user but getting an error when the view is async. Code: from django.http import JsonResponse async def archive(request): user = request.user return JsonResponse({'msg': 'success'}) error message: django.myproject.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. What I tried: from django.http import JsonResponse from asgiref.sync import sync_to_async async def archive(request): # user = sync_to_async(request.user) # user = sync_to_async(request.user)() # user = await sync_to_async(request.user) user = await sync_to_async(request.user)() return JsonResponse({'msg': 'success'}) Still getting the same error. I want to access the user to check he/she has permission to archive a file. -
How to restrict admin link/button in Django?
This is what I expect: if a user has position "1" (Admin) the nav menu in home.html must show "Admin" link to an admin page. If a user has position "2" (User) it won't show the link. But when I run server this code generate as many Admin links as there are registered users. I want only one link for currently logged-in user to be shown. How can I do that? I know that there's something wrong with "for user in position", but how to fix it for currently logged-in user? models.py class Profile(models.Model): positions = ( ('1', 'Admin'), ('2', 'User'), ) user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True) image = models.ImageField(default='default.jpg', upload_to='profile_pics') position = models.CharField(max_length=50, default='Position', choices=positions) views.py def home(request): user_position = Profile.objects.all() return render(request, 'home.html', { 'position': user_position, }) home.html {% for user in position %} {% if user.position == '1' %} <a class="nav-link" aria-current="page" href="/admin">Admin</a> {% endif %} {% endfor %} -
Django: Dates don't change correctly when changing Timezone
When I change the timezone in my django project the dates do change correctly. When the timezone is set to 'UTC' the dates are displayed like this: This is correct. As you can see these are also the dates which are specified in my database: But when I change the settings to: LANGUAGE_CODE = 'nl' TIME_ZONE = 'Europe/Amsterdam' USE_I18N = True USE_L10N = True USE_TZ = True The dates inside my application now change to the image below. Only the first two dates are displayed in the correct way, even though nothing has changed except for the timezone. Does anyone know why this happens, and how I can solve this? -
drf: Add a non-model field in Serializer
If receiver==me then the name will be sender name, else name will be receiver name. I can do it in views.py, but is it possible in serializers.py? here is my code: models.py: class Message(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sender') receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name='receiver') body = models.TextField(max_length=1000) date = models.DateTimeField(auto_now_add=True) seen = models.BooleanField(default=False) class Meta: ordering = ('date',) serializers.py: class SimpleUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id','first_name', 'last_name') class GetMessageSerializer(serializers.ModelSerializer): sender = SimpleUserSerializer() receiver = SimpleUserSerializer() #name = ....???? class Meta: model = Message fields = ('sender','receiver','body','date','seen') -
How to fix Field 'id' expected a number but got 'description' in django admin panel
In django admin I am trying to pre populate values from model MetaTag to model ModelSeoMetadatum using model forms and django-autocomplete-light library dal library. my models: class MetaTag(models.Model): name = models.CharField(max_length=50, null=True, blank=True) property = models.CharField(max_length=50, null=True, blank=True) def __str__(self): if self.name !=None and self.property == None: return str(self.name) elif self.name == None and self.property != None: return str(self.property) else: 'name : ' + str(self.name) + ' , property : ' + str(self.property) class SeoMetadatum(models.Model): class Meta: verbose_name_plural = "SEO Metadata" path = models.CharField(max_length=100, null=True, blank=True) name = models.CharField(max_length=50, null=True, blank=True) property = models.CharField(max_length=50, null=True, blank=True) content = models.CharField(max_length=200, null=True, blank=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True, blank=True) object_id = models.UUIDField(null=True, blank=True) content_object = GenericForeignKey('content_type', 'object_id') class ModelSeoMetadatum(SeoMetadatum): class Meta: verbose_name_plural = "Model Metadata" proxy = True my form class ModelSeoMetadatumForm(forms.ModelForm): name = ModelChoiceField(required=False,queryset=MetaTag.objects.exclude(name__isnull=True).values_list('name' , flat = True).distinct(),widget=autocomplete.ModelSelect2(url='seo:name-autocomplete')) class Meta: model = ModelSeoMetadatum fields = ('content_type', 'object_id', 'name', 'content', 'property') my admin @admin.register(ModelSeoMetadatum) class ModelSeoMetadatumAdmin(admin.ModelAdmin): list_display = ('id', 'name', 'content', 'property', 'content_object') fields = ('content_type', 'object_id', 'name', 'content', 'property') form = ModelSeoMetadatumForm my url urlpatterns = [ path('name-autocomplete/', NameAutocomplete.as_view(),name='name-autocomplete'), ] my view class NameAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): if not self.request.user.is_authenticated: return MetaTag.objects.none() qs = MetaTag.objects.all() if self.q: qs = qs.filter(Q(name__istartswith=self.q) | Q(name__icontains=self.q)) … -
Why does Django causes my materialize link to appear blue when I hover over them?
as you can see when I hover over the dropdown box the link becomes blue, what could be the cause of this?? I am using Django with this maybe that could be causing problems I tried it in a document with only the materialize header and it works just fine: Here is the code: <head> <!--Import Google Icon Font--> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!-- Compiled and minified CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> <!--Let browser know website is optimized for mobile--> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> </head> <body> <!-- Dropdown Structure --> <ul id="dropdown1" class="dropdown-content"> <li><a href="#!">one</a></li> <li><a href="#!">two</a></li> <li class="divider"></li> <li><a href="#!">three</a></li> </ul> <nav> <div class="nav-wrapper"> <a href="#!" class="brand-logo">Logo</a> <ul class="right hide-on-med-and-down"> <li><a href="sass.html">Sass</a></li> <li><a href="badges.html">Components</a></li> <!-- Dropdown Trigger --> <li><a href="#" class="dropdown-trigger" data-target="dropdown1">Dropdown<i class="material-icons right">arrow_drop_down</i></a></li> </ul> </div> </nav> <!-- Compiled and minified JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script> <script> M.AutoInit() $(".dropdown-trigger").dropdown(); </script> </body> When I combine it with my Django main page it messes up, what should I remove/add? Main page header: <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Stock Trading Website</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="{%static "/css/main.css"%}"> <!-- Compiled and minified JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script> … -
Approve application method in Django
Dear Django User how can I put an approve function in my project? My code is below: Model: class ApproveJob(models.Model): PENDING = 'pending' ACTIVE = 'approved' CHOICES_STATUS = ( (PENDING, 'Pending'), (ACTIVE, 'Approved'), ) approve = models.ForeignKey(Application, related_name='approved_job', on_delete=models.CASCADE) status = models.CharField(max_length=20, choices=CHOICES_STATUS, default=PENDING) def __str__(self): return str(self.approve) -
How to update several objects with one form in Django?
I create a customer model and a function for assign a customer to a user. Assign function is update user field in Customer model. This Customer model has a country field. I want to assign the customers in the same country to a user with one form. For doing that I have listing all countries and a form for assign operation? How can I do that? models.py class Customer(models.Model): customer_name = models.CharField(max_length=20) country = models.ForeignKey(Country, on_delete=models.CASCADE, null=True, unique=False) ... user = models.ForeignKey(UserProfile, on_delete=models.CASCADE, blank=True, null=True) And this is my form for assigning customers one by one: views.py def customer_list(request): current_user = request.user userP = UserProfile.objects.get_or_create(username=current_user) customer_list = Customer.objects.filter(company=userP[0].company) # Assign form = AssignForm(request.POST or None) if request.POST: customer_id = request.POST.get('customer_id', None) customer = Customer.objects.get(id=customer_id) user = UserProfile.objects.get(id=request.POST.get('user', None)) customer.user = user customer.save() form.save() return redirect('user:customer_list') context = { 'customer_list': customer_list, 'form': form } return render(request, 'customer_list.html', context) customer_list.html <table id="multi-filter-select" class="display table table-striped table-hover grid_" > <thead> <tr> <th>Customer Name</th> <th>Country</th> ... <th>Operations</th> </tr> </thead> <tbody> {% for customer in customer_list %} <tr> <td>{{customer.customer_name}}</td> <td>{{customer.country}}</td> ... <td> ... {% if customer.user == null %} <button type="button" class="btn btn-info" data-toggle="collapse" data-target="#demo{{ forloop.counter }}">&nbsp;Assign&nbsp;&nbsp;&nbsp;&nbsp;</button> {% else %} <button type="button" class="btn btn-success" data-toggle="collapse" … -
Get the user context in all views django?
Im using a template syntax to set the permissions for the topbar of the application like so Top bar permision {% if user.is_authenticated %} # Top bar html code {% endif %} but the problem is that when a user i authenticated they can accress the profile picture and name of another user if they have the correct url:uuid link. I managed to get this fixed by putting this syntax in the template {% if object == request.user %} {% if object.pk %} {% endif %} {% endif %} This fixed the issue on the pages where the request.user can be accressed from the profile view. How can i accress the request.user in all the views at once? -
nginx+gunicorn+django error Not Found: /static/.. file
I built a python web framework by using django, and I want to deploy it with nginx and gunicorn. However, I keep getting prompted for error about "Not Found: /static/answer/result.png". If I didn't use nginx adnd gunicorn I wouldn't get this error. I don't know what went wrong, please help me, thank you. (1) settings.py file: 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.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'tuh%ati6x38&q8t4sr$h46m_lc$r!dpx@#aobx#%dj(vflho2z' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ["127.0.0.1", "192.168.43.90", "192.168.2.229"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "gunicorn", 'UserProfile', 'ImageRecognition', "KuaiChao", "HuaXiao" ] 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 = 'LPAI.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], '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 = 'LPAI.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', … -
ARA Exception even though the env variable and the API are set properly
What is the issue? I am facing this issue: ~ # ansible-playbook test_playbook.yml -vv ansible-playbook 2.10.6 config file = None configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules'] ansible python module location = /root/.local/lib/python3.8/site-packages/ansible executable location = /root/.local/bin/ansible-playbook python version = 3.8.7 (default, Mar 2 2021, 10:13:07) [GCC 10.2.1 20201203] No config file found; using defaults [WARNING]: No inventory was parsed, only implicit localhost is available [WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all' Operations to perform: Apply all migrations: admin, API, auth, contenttypes, db, sessions Running migrations: No migrations to apply. Skipping callback 'default', as we already have a stdout callback. Skipping callback 'minimal', as we already have a stdout callback. Skipping callback 'oneline', as we already have a stdout callback. PLAYBOOK: test_playbook.yml ***************************************************************************************************************************************************************************************************************** 2021-03-09 17:47:40,379 ERROR ara.clients.http: Failed to post on /api/v1/playbooks: {'ansible_version': '2.10.6', 'arguments': {'version': None, 'verbosity': 2, 'ask_pass': False, 'private_key_file': None, 'remote_user': None, 'connection': 'smart', 'timeout': 10, 'ssh_common_args': '', 'sftp_extra_args': '', 'scp_extra_args': '', 'ssh_extra_args': '', 'force_handlers': False, 'flush_cache': False, 'become': False, 'become_method': 'sudo', 'become_user': None, 'become_ask_pass': False, 'tags': ('all',), 'skip_tags': (), 'check': False, 'syntax': False, 'diff': False, 'inventory': ('/etc/ansible/hosts',), 'listhosts': False, 'subset': None, 'extra_vars': "Not saved … -
How can I show specific users data into the serializer through django?
I am trying to create a portfolio of users for the stock market. I have custom users model like this: class CustomUsers(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, db_index=True,null=True) phone_no = models.CharField(max_length=50,null=True,unique=True) first_name = models.CharField(max_length=120, blank=True) last_name = models.CharField(max_length=120, blank=True) is_admin = models.BooleanField('admin', default=False) is_active = models.BooleanField( _('active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.' ), ) is_staff = models.BooleanField( _('staff status'), default=False, help_text=_( 'Designates whether the user can log into this admin site.' ), ) date_joined = models.DateTimeField( _('date joined'), default=timezone.now ) objects = CustomUserManager() def get_full_name(self): return (self.first_name +" " +self.last_name) I have another app called portfolio and I have two models in it. They are like this: class MyShares(models.Model): TYPE = ( ('IPO',_('IPO')), ('FPO', _('FPO')), ('Secondary',_('Secondary')), ('Bonus', _('Bonus')), ('Rights', _('Rights')), ('Auction', _('Auction')) ) SHARE_STATUS = ( ('Owned',_('Owned')), ('Sold',_('Sold')) ) user = models.ForeignKey("users.CustomUser", verbose_name=_("User"), on_delete=models.CASCADE, related_name='my_shares') stock_symbol = models.ForeignKey("finance.Organization", verbose_name=_("Stock Symbol"), on_delete=models.CASCADE) buy_date = models.DateField(_("Buy Date"), auto_now=False, auto_now_add=False) sell_date = models.DateField(_("Sell Date"), auto_now=False, auto_now_add=False, null=True, blank=True) buy_price = models.FloatField(_("Buy Price")) sell_price = models.FloatField(_("Sell Price"),null=True,blank=True) quantity = models.PositiveIntegerField(_("Quantity")) share_type = models.CharField(_("Type"), choices=TYPE, default='IPO', max_length=50) share_status = models.CharField(_("Status"),choices=SHARE_STATUS,default='Owned', max_length=50) def __str__(self): # if self.user.first_name: # return self.user.get_full_name() return self.stock_symbol.symbol class Portfolio(models.Model): … -
how to install djangorestframework-gis-distance
hi i am on ubuntu and i tried to install djangorestframework-gis-distance i followed the instructions and installed the dependencies which installed fine. But when i install djangorestframework-gis-distance it gives an error of ERROR: Command errored out with exit status 1: command: /home/aarush/git_fudo/food1_back/food1_back/env/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-ntgn7sle/djangorestframework-gis-distance/setup.py'"'"'; __file__='"'"'/tmp/pip-install-ntgn7sle/djangorestframework-gis-distance/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base pip-egg-info cwd: /tmp/pip-install-ntgn7sle/djangorestframework-gis-distance/ Complete output (5 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-install-ntgn7sle/djangorestframework-gis-distance/setup.py", line 9, in <module> from pip.req import parse_requirements ModuleNotFoundError: No module named 'pip.req' ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. which basically says i think that there is no file called pip.req. is there another way i can install djangorestframework-gis-distance? -
How to run a long process/function on button click django
Im trying to do a django website in which: I take a user input from the template (done) Save the input in the view (done) On a button click, user starts a function that send a api request every x seconds and if the function find a different api response then show it in template as status. And i have no idea how to achieve the 3rd point. This is how the api request function looks like: def function(zapytaniex,fraza,kategoria): starttime = time.time() data1 = zapytaniex while True: data2 = apirequest(fraza = fraza, categoryid = kategoria) if data1 != data2: context["status"] = "got new offer" elif data1 == data2: context["status"] = "still nothing" time.sleep(120.0 - ((time.time() - starttime) % 120.0)) As you can see this function send the api request every 2 minutes and I want to run this function when user clicks a button and then update a status context in a template WITHOUT refreshing the whole page. I tried to run it with threading but the page keep loading when the thread in working. Thanks for any help and ideas! -
The view admission.views.UpdateEducation didn't return an HttpResponse object. It returned None instead
What is the problem in this.... View.Py def UpdateEducation(request, id=None): context = {} user_obj = request.user if not user_obj.is_authenticated: return redirect('login') user_id = Applicant.objects.filter(app_id = user_obj.app_id).first() applicant = ProfileInfo.objects.filter(user=user_id).first() if request.POST: form = EducationForm(request.POST, instance=applicant) if form.is_valid(): obj = form.save(commit=False) obj.applicant_info = applicant obj.save() return redirect('profile') else: context['education_form'] = form else: try: user_info = ApplicantEducation.objects.filter(applicant_info = applicant).get() form = EducationForm( initial={ 'institute_name': user_info.institute_name, 'marks_percentage' : user_info.marks_percentage, 'affilation_with' : user_info .affilation_with, 'date_completion':user_info.date_completion, 'degree_details' : user_info.degree_details, } ) context['education_form']= form except: form = EducationForm() context['education_form']= form return render(request, 'admission/signup.html', context) i have a model called ApplicantEducation for which i am using EducationForm. This view function listed above is intended to store education details, but it comes up with error. What missing here, please take a look.... -
Sum and store values in another table
I am new to Django. My query is I store some quantity of components in a table. I want to sum the quantity sorting it by components and then use the summed quantity in some other table to do further calculations. How can I achieve this.. #views.py class PurchaseCreateView(CreateView): model = Purchase fields = '__all__' success_url = reverse_lazy("purchase_form") def get_context_data(self,**kwargs): context = super().get_context_data(**kwargs) context['purchases'] = Purchase.objects.all() return context #models.py class Purchase(models.Model): purchase_date = models.DateField() invoice_no = models.CharField(max_length=200,unique=True) supplier =models.ForeignKey(Supplier,on_delete=models.CASCADE) components = models.ForeignKey(Components,on_delete=models.CASCADE) quantity = models.PositiveIntegerField() remarks = models.TextField(max_length=500,blank=True,null=True) def __str__(self): return str(self.pk) # Below is the Model where I want to use the summed quantity for further calc class IntermediateStage(models.Model): producttype = models.ForeignKey(ProductType,on_delete=models.CASCADE) components = models.ForeignKey(Components,on_delete=models.CASCADE) processingstage = models.ForeignKey(ProcessingStage,on_delete=models.CASCADE) unitsrequired = models.PositiveIntegerField() quantity = models.PositiveIntegerField(blank = True) total_quantity = models.IntegerField(blank= True) class Meta: unique_together = [['producttype','components','processingstage']] def __str__(self): return str(self.id) -
applying selected model data to form - Django
I am working on a printing ordering service website in Django 3.1 . I am stuck on order page. On order page I want to provide option to user that he can create either a custom order from given option otherwise he can select from packages one of the package and that package data will be applied to the form and that form will be submitted as order. But I don't know how to achieve that functionality. models.py class Packages(models.Model): package_ID = models.AutoField("Package ID", primary_key=True) package_Name = models.CharField("Package Name", max_length=30, null=False) attribute_values = models.JSONField("Item Details JSON", max_length=500, null=False) package_Price = models.IntegerField("Package Price", null=False, default=0.00) quantity = models.IntegerField("Quantity", null=False, default=00) prod_ID = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name="Product ID (FK)") class Order(models.Model): order_id = models.AutoField("Order ID", primary_key=True) user_id = models.ForeignKey(User, on_delete=models.CASCADE, null=False, verbose_name="Customer ID") prod_id = models.ForeignKey(Product, on_delete=models.CASCADE, null=False, verbose_name="Product ID") quantity = models.IntegerField('Product Quantity', null=False, default=0) attribute_value = models.CharField("Item Details JSON", max_length=2000, null=False) This is my views I am storing custom order in order table , here I am packing size and color value in dictionary and storing it as JSON in model. views.py def order(request, id): products = Product.objects.all() sizesList = [] ColorsList = [] Packages_list = [] quantity = 0 try: … -
How to download PgAdmin 4 database backup in Django
import os def Download_db(request): os.system("pg_dump -- kite=postgresql://postgres:root@127.0.0.1:5432/test>C:\Users\hp\Desktop\dumpfile3.dump" ) return HttpResponse("done") -
ModuleNotFoundError: No module named 'model_mixins'
Python 3.8 models.py from gettext import gettext import omnibus.model_mixins.general as general from django.db import models import model_mixins class Client(general.NameMixin, general.FlagMixin, model_mixins.DirMixin, general.ArchivedMixin, general.CommentMixin, models.Model): class Meta: verbose_name = gettext("Client") verbose_name_plural = gettext("Clients") model_mixins.py from django.db import models from django.db.models import Index from django.utils.translation import gettext class DirMixin: dir = models.CharField(max_length=30, unique=True, verbose_name=gettext("Target directory")) class Meta: abstract = True Index(fields=['dir', ]) **tree** ├── ads6 │ ├── asgi.py │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-38.pyc │ │ ├── settings.cpython-38.pyc │ │ └── urls.cpython-38.pyc │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── clients │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ └── __init__.py │ ├── model_mixins.py │ ├── models.py │ ├── __pycache__ │ │ ├── __init__.cpython-38.pyc │ │ └── models.cpython-38.pyc │ ├── tests.py │ └── views.py ├── db.sqlite3 **migrations** (venv) michael@michael:~/PycharmProjects/ads6/ads6$ python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.8/importlib/__init__.py", … -
Access variable in the forms class?
How to get the value of ModelChoiceField in Django forms class. I have one ModelChoiceField in my forms.ModelForm class: class mStockForm(forms.ModelForm): mStock_product = forms.ModelChoiceField( queryset=mProduct.objects.filter(), label='Select Milk Product', help_text="Choose from the list of milk products", required=True, ) #---------------------------Want to access mStock_Product'''''''''''''''''''''''# value = mStock_product.value #<------------Here -
Code for Python image upload handler with tinymce
Please help me with code for locally upload image of tinymce. I use tinymce for WYSIWYG Editors on admin page of django. It work. But I cannot upload image from the local computer. I search on google and have some result for php code (https://www.tiny.cloud/docs/advanced/php-upload-handler/). I cannot find example code for python. If I want to upload a local image, I must config images_upload_url in settings.py as below: TINYMCE_DEFAULT_CONFIG = { ... 'images_upload_url': os.path.join(BASE_DIR, "script/upload.py"), ... } But I don't know where I place upload.py file and how I can config path. And How to code upload.py correctly. -
Make a field in fieldset of ModelAdmin required in Django
I need to make some fields in the fieldset variable of a ModelAdmin class as required so that the user cannot create or update a user instance if those fields are not selected in the form. How can I do that? class MyUserChangeForm(UserChangeForm): class Meta(UserChangeForm.Meta): model = User class MyUserCreationForm(UserCreationForm): error_message = UserCreationForm.error_messages.update({ 'duplicate_username': 'This username has already been taken.' }) class Meta(UserCreationForm.Meta): model = User def clean_username(self): username = self.cleaned_data["username"] try: User.objects.get(username=username) except User.DoesNotExist: return username raise forms.ValidationError(self.error_messages['duplicate_username']) @admin.register(User) class UserAdmin(AuthUserAdmin): fieldsets = AuthUserAdmin.fieldsets + ( (None, {'fields': ('user_type', 'country')}), ) add_form = MyUserCreationForm Here I want to make country and user_type as required in the admin panel. How can I do that? -
Image is not getting saved in the database django
I am trying to upload an image to the database. While posting the data I am not getting any error. Image tag in html <div class="text-center"> <h6>Upload a different photo...</h6> <input type="file" class="form-control" name="user_img"> </div> UserProfile model # User profile class UserProfile (models.Model): # user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) user_img = models.ImageField(null=True, blank=True, upload_to='static/images') name = models.CharField(max_length=100) emailID = models.CharField(max_length=100) phone = models.CharField(max_length=15) college_name = models.CharField(max_length=200) branch = models.CharField(max_length=100) urls.py from django.contrib import admin from django.urls import path, include # For user profile from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('colos.urls')), path('accounts/', include('allauth.urls')), ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) settings.py # For user images MEDIA_URL = '/images/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') views.py # edit user profile def edit_profile(request): try: # checking if the user exist in UserProfile through the logged in email id user_data = UserProfile.objects.get(emailID = request.user.email) if request.POST.get('action') == 'post' and request.FILES: name = UserProfile.objects.all() response_data = {} # user profile image start user_img = request.FILES['user_img'] # user profile image end name = request.user.username emailID = request.user.email phone = request.POST.get('phone') college_name = request.POST.get('college_name') branch = request.POST.get('branch') response_data['user_img'] = user_img response_data['name'] = name response_data['emailID'] = emailID response_data['phone'] = phone response_data['college_name'] = … -
Nested management commands in Django
Is there anyway to create nested management commands in Django, similar to what the docker and kubectl have? For example, let's say I need to have the following structure: |-->manage.py |-->restaurant |-->list |-->get |-->employee |-->list |-->get |-->delete The following commands should all be possible: ./manage.py -h ./manage.py restaurant -h ./manage.py restaurant list ./manage.py employee list ./manage.py restaurant get "" ./manage.py employee delete tiffany The argparse subparser looks promising but I feel like there should be an easier way using python modules in the app/management/commands or something like that. -
what is the best solution for GNU gettext installation in windows?
in windows for a django project on pycharm, my Django and dependencies are installed on venv. I wanted to modify one .po file and test it if it's working or not, it seems that this change needs to commit by this command: *django-admin makemessages -l -ja* I tried it and I faced with this error: "CommandError: Can't find msguniq. Make sure you have GNU gettext tools 0.15 or newer installed." I tried to install gettext for my project but it didn't work. pip install python-gettext didn't work as well. and some of the answers for similar issue were not clear I want to know the best solution for this situation ...