Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filter query between two values
I'm working on django but can't figure how to write a query , I'm trying to get value between range of values store +----+-------------+-----------+ | id | value up | value down| +----+-------------+-----------+ | 1 | 100 | 200 | +----+-------------+-----------+ | 2 | 150 | 300 | +----+-------------+-----------+ | 3 | 7000 | 7500 | +----+-------------+-----------+ How suppose I have value 290 , how do I get Id from range of 150 to 300 -
Does django save method changes require new migration?
After changing a model save method, is it required to run the makemigration command? In which case (if there are) does changes in save method involve database migrations? -
What is the best way to give user interface to a python chatbot?
I made a chatbot using Python and TensorFlow. It works fine and I have the py file ready but how do I give it interface. I want to launch it as a web application. How do I do it? This is probably a very silly question for many of you. Thank you in advance Here is the code for the chatbot just in case import nltk from nltk.stem.lancaster import LancasterStemmer stemmer = LancasterStemmer() import numpy import tflearn import tensorflow import random import json import pickle with open("intents.json") as file: data = json.load(file) try: with open("data.pickle", "rb") as f: words, labels, training, output = pickle.load(f) except: words = [] labels = [] docs_x = [] docs_y = [] for intent in data["intents"]: for pattern in intent["patterns"]: wrds = nltk.word_tokenize(pattern) words.extend(wrds) docs_x.append(wrds) docs_y.append(intent["tag"]) if intent["tag"] not in labels: labels.append(intent["tag"]) words = [stemmer.stem(w.lower()) for w in words if w != "?"] words = sorted(list(set(words))) labels = sorted(labels) training = [] output =[] out_empty = [0 for _ in range(len(labels))] for x, doc in enumerate(docs_x): bag = [] wrds = [stemmer.stem(w) for w in doc] for w in words: if w in wrds: bag.append(1) else: bag.append(0) output_row = out_empty[:] output_row[labels.index(docs_y[x])] = 1 training.append(bag) output.append(output_row) … -
Django error: I want to update profile picture along with other account details, but its showing error
views.py def profile_edit(request): if not request.user.is_authenticated: return redirect('login') context = {} if request.POST: form = AccountUpdateForm(request.POST, request.FILES, instance=request.user) if form.is_valid(): form.initial = {'email':request.user.email, 'first_name':request.user.first_name, 'last_name':request.user.last_name, 'profile_pic':request.user.profile_pic} form.save() context['success_group'] = "Your details have been updated" else: form = AccountUpdateForm(initial={'email':request.user.email, 'first_name':request.user.first_name, 'last_name':request.user.last_name, 'profile_pic':request.user.profile_pic}) context['account_form'] = form return render(request,'accounts/accountpage_edit.html', context) forms.py class AccountUpdateForm(forms.ModelForm): class Meta: model = Account fields = ['email', 'first_name', 'last_name', 'profile_pic'] def clean_email(self): email = self.cleaned_data['email'] try: account = Account.objects.exclude(pk=self.instance.pk).get(email=email) except Account.DoesNotExist: return email raise forms.ValidationError('Email "%s" is already in use.' % account) def clean_first_name(self): if self.is_valid(): first_name = self.cleaned_data['first_name'] def clean_last_name(self): if self.is_valid(): last_name = self.cleaned_data['last_name'] def clean_profile_pic(self): if self.is_valid(): profile_pic = self.cleaned_data['profile_pic'] I am a beginner and not sure how to continue doing this. The problem before was the picture was not getting uploaded but after some tweaks its now showing this error: The view accounts.views.profile_edit didn't return an HttpResponse object. It returned None instead. Can anyone guide how to make this happen? Thanks in advance! -
Cannot open file in S3 bucket
I'm trying to open a file in an S3 bucket in a view using the following filename = static('post_codes/towns.csv') contents = list(unicode_csv_reader(open(filename,encoding="utf8"))) I get a file not found, no such file or directory, but the file does exist and if I enter the url provided back by the error message it opens the file. What am I doing wrong? Note, unicode_csv_reader is just a simple function to extract the data def unicode_csv_reader(utf8_data, dialect=csv.excel, **kwargs): csv_reader = csv.reader(utf8_data, dialect=dialect, **kwargs) for row in csv_reader: yield [cell for cell in row] -
Convert string to date django template
I'm trying to convert string to date in template using template tag but it doesn't work {% load templat_tag_file %} <input name="range2" type="date" {% if request.Get.range2 %} value="{{ request.Get.range2|convert_str_date }}"{% endif %}/> my templat_tag_file.py : from datetime import datetime register = template.Library() @register.filter def convert_str_date(value): return datetime.strptime(value, '%Y-%m-%d').date() -
Django Display image & image file name in a template
I am trying to display multiple images (20 - 30) with the image file also being displayed. I have the images displayed but I am not sure how to get the image file name to display beside it / underneath it. I am new to Django any help would be appreciated. Here's what I have done so far: template.html <div class="container-fluid my-container"> {% filter_images_normal 6 as images %} <div class="row no-pad display-flex my-row"> {% for image in images %} <div class="col-xl-4 col-lg-4 col-md-4 col-sm-4 col- my-col my-col-xl-4 col-lg-4 col-md-4 col-sm-4 col-4 my-col"> <input class="img-thumbnail" type="image" id="image" alt="Image" src="{{ MEDIA_URL}}{{ image }}"> <p>Image name file here</p> </div> {% endfor %} </div> </div> filter_images.py (template tag) @register.simple_tag def filter_images_normal(count=3): valid_extensions = ('.jpg', '.jpeg', '.png', '.gif') rand_dir = '/static/app_filter/images/normal/' path = '/app_filter/static/app_filter/images/normal/' files = [f for f in os.listdir(settings.BASE_DIR + path) if f[f.rfind("."):] in valid_extensions] # print(random.sample(files, count)) print(rand_dir) return [rand_dir + filename for filename in random.sample(files, count)] -
How i can send recently save data into template in same view function in django
view.py In the below code, I'm saved my recent data in model and create a dictionary order = order.save() because I can use this in my template. When I run the code the order is having ```None`` value. What i can do for it. def post(self, request, product_id): product = Product.objects.get(id=product_id) if request.POST['address'] and request.POST['quantity']: order = Order() order.or_proName = product.pro_name order.or_companyName = product.companyName order.or_quatity = request.POST['quantity'] order.or_quatity = int( order.or_quatity) orderPrice = order.or_quatity*product.Sale_Price order.or_bill = 100 + orderPrice order.pub_date = timezone.datetime.now() product.Quantity -= order.or_quatity product.save() order = order.save() args = {'order':order} return render(request, self.red_templateName, args) -
Reading and saving data to a Django model
I am trying to understand how to save data into my Django models. I have a form that display Questions and choices from my models. I want the user to answer the question and to be saved in the Answer model. Here are my models class Question(models.Model): question_text = models.CharField(max_length=200) caption = models.CharField(max_length=200, default="this is a caption") choices = models.ManyToManyField(Choice) vis_image = models.ImageField(default= "this is an image", null=False, blank=False, upload_to="static/study/img") def __str__(self): return self.question_text class Condition(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Participant(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) condition = models.ForeignKey(Condition, on_delete=models.CASCADE) score = models.IntegerField(default=0) def __str__(self): return self.user.username class Answer(models.Model): participant = models.ForeignKey(Participant, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) answer = models.CharField(max_length=200, null=True) completion_time = models.FloatField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.answer views.py @login_required def LPSC_VIEW1(request): participant=Participant.objects.get(user=request.user) #GET the first question based on the participant condition if participant.condition.name == 'LPN': First_question= Question.objects.get(id=1) all_choices = First_question.choices.all() context = {'First_question': First_question, 'all_choices': all_choices} return render(request, 'study/FirstQN.html', context) else: First_question= Question.objects.get(id=11) all_choices = First_question.choices.all() context = {'First_question': First_question, 'all_choices': all_choices} return render(request, 'study/FirstQSC.html', context) FirstQN.html <form method="POST"> {% csrf_token %} <label> {{First_question}} </label> <img src="{{ First_question.vis_image.url }}" style= "height: 600px; width: … -
During deploying Django blog on heroku showes me errors
When I deploy app in heroku show me this error remote: ERROR: Could not find a version that satisfies the requirement apturl==0.5.2 (from -r /tmp/build_16067d5dbf345d8d906970e4d4f44d30/requirements.txt I searched on internet to finding the solution of that problem but can't successfully find this. So I show you what steps I had do for deploy app in heroku I typed in terminal heroku login pip3 freeze pip3 freeze > requirements.txt Then for instaling gunicorn type in terminal pip3 install gunicorn Then make a file in root directory write name is Procifle in which I write web: gunicorn django_project.wsgi Then my heroku blog name heroku git:remote -a naqviblog I also show you my requirements.txt file apturl==0.5.2 asgiref==3.2.3 asn1crypto==0.24.0 blinker==1.4 boto3==1.9.96 botocore==1.12.96 Brlapi==0.6.7 certifi==2018.8.24 chardet==3.0.4 command-not-found==0.3 cryptography==2.3 cupshelpers==1.0 defer==1.0.6 distro==1.3.0 distro-info===0.21ubuntu2 dj-database-url==0.5.0 Django==3.0.4 django-crispy-forms==1.9.0 django-heroku==0.3.1 django-storages==1.7.1 docutils==0.14 entrypoints==0.3 f.lux-indicator-applet==1.1.11rc0 galternatives==1.0.3 gunicorn==20.0.4 httplib2==0.11.3 idna==2.6 jmespath==0.9.3 keyring==17.1.1 keyrings.alt==3.1.1 language-selector==0.1 launchpadlib==1.10.6 lazr.restfulclient==0.14.2 lazr.uri==1.0.3 lightdm-gtk-greeter-settings==1.2.2 louis==3.8.0 macaroonbakery==1.2.1 Mako==1.0.7 MarkupSafe==1.1.0 netifaces==0.10.4 oauth==1.0.1 oauthlib==2.1.0 olefile==0.46 pbr==5.4.4 pexpect==4.6.0 Pillow==5.4.1 protobuf==3.6.1 psycopg2==2.7.7 pycairo==1.16.2 pycrypto==2.6.1 pycups==1.9.73 PyGObject==3.32.0 PyJWT==1.7.0 pymacaroons==0.13.0 PyNaCl==1.3.0 pyOpenSSL==19.0.0 pyRFC3339==1.1 python-apt===1.8.5-ubuntu0.3 python-dateutil==2.7.3 python-debian==0.1.34 python-decouple==3.3 pytz==2018.9 pyxattr==0.6.1 pyxdg==0.25 PyYAML==3.13 reportlab==3.5.18 requests==2.21.0 requests-unixsocket==0.1.5 s3transfer==0.2.0 SecretStorage==2.3.1 simplejson==3.16.0 six==1.12.0 sqlparse==0.3.1 system-service==0.3 systemd-python==234 testresources==2.0.1 ubuntu-advantage-tools==19.2 ubuntu-drivers-common==0.0.0 ufw==0.36 unattended-upgrades==0.1 urllib3==1.24.1 usb-creator==0.3.3 virtualenv==15.1.0 wadllib==1.3.3 whitenoise==4.1.2 xkit==0.0.0 youtube-dl==2019.1.17 zope.interface==4.3.2 Then … -
How to populate selected data and x other data in django ModelChoiceField form?
I want to populate only few data in django ModelChoiceField form including the selected one in my update form. This is my form class BaseManageSiteForm(ModelForm): """Custom organisation creation form.""" class Meta: # noqa D106 model = Tenant fields = ('domain', 'logo', 'store_description', 'store_tier', 'site_theme', ) widgets = { 'logo': MetronicAvatar(), } class UpdateSiteForm(BaseManageSiteForm): """RegistrationSiteForm.""" site_theme = forms.ModelChoiceField(Theme.objects.all(), empty_label=None) store_tier = forms.ChoiceField(choices=StoreTier.choices, disabled=True) domain = forms.CharField(disabled=True) What i have done is, i tried to limit the data with queryset ModelChoiceField with Theme.objects.all()[:3] It works for populate only 3 data, but the data that selected wasn't populate. How can i resolve this problem? -
Avoid PUT response data to contain full data with nested serializer and generic views (Django Rest Framework)
I'm building an API based on a RetrieveUpdateAPIView with a Writable nested serializers. The issue I have is that when I make a PUT request, the response data contains all the data of the serializer... And the amount of those data is pretty big. How can I modify my code to avoid this behavior? I imagine that this should be at the level of the view? I would preferably stick to generic views. Thanks for your support. For the record, Here is the serializer code: # DatetimeValue serializer class DatetimeValueSerializer(serializers.ModelSerializer): class Meta: model = DatetimeValue fields = ['date_time', 'value'] # Serializer that includes time series header and date time values class TimeSeriesValueSerializer(serializers.ModelSerializer): values = DatetimeValueSerializer(many=True) class Meta: model = TimeSeries fields = ['id', 'name', 'values'] def update(self, instance, validated_data): ts_name = validated_data.pop('name') try: time_series = TimeSeries.objects.get(name=ts_name) except ObjectDoesNotExist: raise ValidationError(_(f"Time series doesn't exist")) values_data = validated_data.pop('values') for datetime_value in values_data: try: DatetimeValue.objects.create(time_series=time_series, **datetime_value) except IntegrityError: raise ValidationError(_(f"ERROR in 'date_time' and/or 'value' provided. " f"'date_time' has to be a correct date time format and 'value' a float. " f"A 'date_time' has to be unique for a given time series")) return time_series And the view code: # View to get time series … -
Problems to cover the tests
I am working with Django 3.0.3 and have created a few tests to test my views. I wanted to have the metrics for the coverages, so I installed (with pip) the module coverage. With the tests there is no problem it solves them perfectly: >python manage.py test uMap Creating test database for alias 'default'... 2020-04-02 11:10:20,748 asyncio DEBUG Using selector: SelectSelector System check identified no issues (0 silenced). ..... ---------------------------------------------------------------------- Ran 5 tests in 1.372s OK Destroying test database for alias 'default'... The problem is when trying to cover. According to the python documentation, the way to run it is as follows (but it gives me error in manage.py): coverage run --source='.' manage.py test uMap Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "c:\users\jalvarfe\appdata\local\continuum\anaconda3\envs\py-usim\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "c:\users\jalvarfe\appdata\local\continuum\anaconda3\envs\py-usim\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "c:\users\jalvarfe\appdata\local\continuum\anaconda3\envs\py-usim\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "c:\users\jalvarfe\appdata\local\continuum\anaconda3\envs\py-usim\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "c:\users\jalvarfe\appdata\local\continuum\anaconda3\envs\py-usim\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "c:\users\jalvarfe\appdata\local\continuum\anaconda3\envs\py-usim\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, … -
How to test if view is able to create a new entity in the db?
I have to do basic unit testing in order to get my code coverage higher. I do not need to do anything fancy. Just the bare minimum is required. So, in this case if I am able to hit my view successfully, then that is all I need to do. Agile team is nested under Team as you can see in the models.py. models.py - class Organization(models.Model): orgname = models.CharField(max_length = 100, blank=True) def __str__(self): return str(self.orgname) class Team(models.Model): teamID = models.AutoField(primary_key=True) teamName = models.CharField(max_length = 100, blank=True) org = models.ForeignKey(Organization, on_delete=models.CASCADE) def __str__(self): return str(self.teamName) class AgileTeam(models.Model): agileTeamID = models.AutoField(primary_key=True) agileTeamName = models.CharField(max_length = 100, blank=True) team = models.ForeignKey(Team, on_delete=models.CASCADE) def __str__(self): return str(self.agileTeamName) views.py - @csrf_exempt def newATeam(request): if request.method == 'POST': param = json.loads(request.body) agileteam = param.get('agileteam') teamname = param.get('teamname') team = Team.objects.get(teamName = teamname) AgileTeam.objects.create(agileTeamName=agileteam, team=team) return JsonResponse(status = 200, data = {}) urls.py - path('ajax/newATeam/', views_admin.newATeam, name='ajax_newATeam'), test_views.py - class TestViews(TestCase): @classmethod def setUpTestData(self): # set-up org ORG_NAMES = ['REVCYCSCH', 'DIABLO', 'BROTHERHOOD'] for org in ORG_NAMES: Organization.objects.create(orgname=org) # set-up team orgModels = Organization.objects.all() TEAM_NAMES = ['Blitzkrieg ', 'Hammerheads', 'Mercenaries'] for i in range(len(TEAM_NAMES)): Team.objects.create(teamName=TEAM_NAMES[i], org=orgModels[i]) # set-up agileteam teamModels = Team.objects.all() AGILE_TEAM_NAMES = ['Barons', 'Exterminators … -
Django Rest Framework refers to default database for checking relationship constraints (for eg. foreign key)
I am using DRF for creating the CRUD APIs and have to deal with multiple databases (having same schema) depending on the request. models.py class CustomerMaster(models.Model): customer_key = models.IntegerField(db_column='CUSTOMER_KEY', primary_key=True) # Field name made lowercase. first_name = models.TextField(db_column='FIRST_NAME', blank=True, null=True) # Field name made lowercase. last_name = models.TextField(db_column='LAST_NAME', blank=True, null=True) # Field name made lowercase. email = models.CharField(db_column='EMAIL', max_length=255, blank=True, null=True) # Field name made lowercase. gender = models.TextField(db_column='GENDER', blank=True, null=True) # Field name made lowercase. dob = models.DateField(db_column='DOB', blank=True, null=True) # Field name made lowercase. phone = models.CharField(db_column='PHONE', max_length=255, blank=True, null=True) # Field name made lowercase. address = models.TextField(db_column='ADDRESS', blank=True, null=True) # Field name made lowercase. ... class Meta: db_table = 'customer_master' def __str__(self): return self.first_name + self.last_name class Folder(models.Model): name = models.CharField(max_length=100) sib_id = models.IntegerField(unique=True, null=True) def __str__(self): return self.name class Segment(models.Model): name = models.CharField(max_length=100) folder = models.ForeignKey(Folder, on_delete=models.CASCADE, null=True) selection = JSONField() createdAt = models.DateTimeField(auto_now_add=True) updatedAt = models.DateTimeField(auto_now=True) createdBy = models.ForeignKey(User, on_delete=models.CASCADE, null=True) contact = models.ManyToManyField(CustomerMaster) sib_id = models.IntegerField(unique=True, null=True) def __str__(self): return self.name serializers.py class SegmentSerializer(serializers.ModelSerializer): contact = serializers.SlugRelatedField(many=True, queryset=CustomerMaster.objects.all(), slug_field='email') createdBy = UserSerializer(required=False) class Meta: model = Segment fields = ('id', 'name', 'folder', 'selection', 'createdAt', 'updatedAt', 'createdBy', 'contact', 'sib_id') def create(self, validated_data): club = self.context['club'] … -
Implementing simple Server Sent Event Stream with Django Channels
Django Channels docs has following basic example of a Server Sent Events. AsyncHttpConsumer from datetime import datetime from channels.generic.http import AsyncHttpConsumer class ServerSentEventsConsumer(AsyncHttpConsumer): async def handle(self, body): await self.send_headers(headers=[ (b"Cache-Control", b"no-cache"), (b"Content-Type", b"text/event-stream"), (b"Transfer-Encoding", b"chunked"), ]) while True: payload = "data: %s\n\n" % datetime.now().isoformat() await self.send_body(payload.encode("utf-8"), more_body=True) await asyncio.sleep(1) I want to accept messages sent via channel_layer and send them as events. I changed the handle method, so it subscribes the new channel to a group. And I'm planning to send messages to the channel layer via channel_layer.group_send But I couldn't figure out how to get the messages sent to the group, within handle method. I tried awaiting for the channel_layer.receive, it doesn't seem to work. class ServerSentEventsConsumer(AsyncHttpConsumer): group_name = 'my_message_group' async def myevent(self, event): # according to the docs, this method will be called \ # when a group received a message with type 'myevent' # I'm not sure how to get this event within `handle` method's while loop. pass async def handle(self, body): await self.channel_layer.group_add( self.group_name, self.channel_name ) await self.send_headers(headers=[ (b"Cache-Control", b"no-cache"), (b"Content-Type", b"text/event-stream"), (b"Transfer-Encoding", b"chunked"), ]) while True: payload = "data: %s\n\n" % datetime.now().isoformat() result = await self.channel_receive() payload = "data: %s\n\n" % 'received' I'm sending the … -
Django- How to use one field from one model to another model?
I have 2 models GeneralUser & UserVoteNews which uses User as foreign key. I want to add a Boolean field in the GeneralUser, and want to access it in the UserVoteNews model. How can I achieve this? class GeneralUser(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ban = models.BooleanField(default=True) class UserVoteNews(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ban = ?? -
On open Edx I am installing an Xblock "S3Downloader_uploader" and receiving an lxml file not found error when I run python makemigrations command
After following all the steps from the readme file in https://github.com/jswope00/s3-uploader-downloader I run: python manage.py lms makemigrations s3uploader_downloader --settings=aws in the cli and I get this error. File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/apps/config.py", line 94, in create module = import_module(entry) File "/usr/lib/python2.7/importlib/init.py", line 37, in import_module import(name) File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/s3uploader_downloader/init.py", line 1, in from .s3uploader_downloader import UploaderDownloaderXBlock File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/s3uploader_downloader/s3uploader_downloader.py", line 18, in from xmodule.modulestore.django import modulestore File "/edx/app/edxapp/edx-platform/common/lib/xmodule/xmodule/modulestore/django.py", line 35, in from xblock_django.user_service import DjangoXBlockUserService File "/edx/app/edxapp/edx-platform/common/djangoapps/xblock_django/user_service.py", line 4, in from django.contrib.auth.models import User File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/contrib/auth/models.py", line 4, in from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/contrib/auth/base_user.py", line 52, in class AbstractBaseUser(models.Model): File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/db/models/base.py", line 110, in new app_config = apps.get_containing_app_config(module) File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/apps/registry.py", line 247, in get_containing_app_config self.check_apps_ready() File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/django/apps/registry.py", line 125, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. -
How to translate Enum string in django?
So I have a model that has a status field, for that I've created an Enum class, like that: class Status(Enum): PENDING_APPROVAL = "PENDING-APPROVAL" PLANNED = "PLANNED" APPROVED = "APPROVED" CHANGED_PLAN = "CHANGED-PLAN" COMPLETED = "COMPLETED" CANCELED = "CANCELED" And then added this class as a choice for the model: status = models.CharField( choices=[(tag.value, tag.name) for tag in Status], max_length=20, verbose_name=pgettext("Order", "Status"), default=Status.PENDING_APPROVAL.value, ) All works fine, but the problem is that once I click on my dropdown to pick a choice from my Enum class, I want for my choices to be translated to the other language of my site. I cannot find how to translate my Enum's class choices to the language that I need. -
What is the need of providing STATIC_ROOT?
Can anyone explain to me the need of providing STATIC_ROOT in a django project? As it seems, Everything works fine if I just declare the STATICFILES_DIRS and not STATIC_ROOT. -
How do I use same decorators on more than one function in python?
I am testing in django and using decorator mock.patch.object() for mocking object methods. I want to use same decorators in another funtion of that class. For this I moved the decorators from function to class. This solved my problem, but now I want to add another test funtion, which should not mock those functions. @mock.patch.object(MyClass, 'class_fun_2') @mock.patch.object(MyClass, 'class_fun_1') class TestClass(testcases.TestCase): def setUp(self): # contains my setup that I want to use in all functions for this test class def test_function_1(self, mocked_class_fun_1, mocked_class_fun_2): # I want to use those mocked functions here def test_function_2(self, mocked_class_fun_1, mocked_class_fun_2): # I want to use those mocked functions here too def test_function_3(self): # I do not want to use those mocked functions here If I do this, it is throwing an error: TypeError: test_function_3() takes 1 positional argument but 3 were given So what should I do, so that I can use the setUp in all functions and mocked funtions in only two funtions? PS: I have shown only 2 mocked funtions, but in reality I am mocking 8 functions, so repetition of mock.patch might not be a good idea. -
How can i print new instance in console after creating a post request from django admin panel
when I post data from Django admin panel. I want to print data always in the console when new instance created from Django admin panel -
how to have different type users?
so I am trying to build a web app for a charity organization and it has multiple types of users including patients,people who wants to donate,employers and three more. how should i build the model,views and the admin view? please help me with the code and thanks a lot for your answers -
Django's Celery Kombu Manually Pub/Sub
I trying to trigger a message queue using kombu Producer.publish() method, but always receive Received and deleted unknown message. Wrong destination?!?, or my setup is wrong? ## in some of the views from celery.execute import send_task class TestAPIView(APIView): def post(self, request, *args, **kwargs): send_task('SampleAdd', [3, 3]) # <-- receive by default queue send_task('OutsideAdd', [1, 1]) # <-- receive by remote queue payload = { 'message': 'hello world', 'args': [6,6] } print("connections:", headers) task_queue = Queue('remote', exchange=Exchange('remote', type='topic'), routing_key='remote_tasks.Add') with Connection(settings.CELERY_BROKER_URL) as conn: with conn.channel() as channel: producer = Producer(channel) producer.publish( payload, exchange=task_queue.exchange, routing_key=task_queue.routing_key, declare=[task_queue] ) # <-- error: wrong destination in remote queue return Response({'data': 'sent'}) # tasks.py from sampleapp import celery_app from celery.execute import send_task @celery_app.task(name='SampleAdd') def add(x, y): print("add: ", x + y) return x + y @celery_app.task(name='OutsideAdd') def outside_add(x, y): print("outside_add: ", x + y) return x + y ##### # settings.py (django) from kombu import Exchange, Queue CELERY_BROKER_URL = "amqp://guest:guest@localhost:5672/" CELERY_RESULT_BACKEND = 'django-db' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERYBEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' CELERY_TASK_DEFAULT_QUEUE = 'default' CELERY_TASK_DEFAULT_EXHANGE_TYPE = 'topic' CELERY_TASK_DEFAULT_ROUTING_KEY = 'default' CELERY_CREATE_MISSING_QUEUES = True CELERY_TASK_QUEUES = ( Queue('default', exchange=Exchange('default', type='topic'), routing_key='default'), Queue('remote', exchange=Exchange('remote', type='topic'), routing_key='remote_tasks.#'), ) CELERY_TASK_ROUTES = { "OutsideAdd": { "queue": "remote", … -
Calculate stock quantity
I have two models containing different types of transactions that i want to use as the base for calculation of quantities for my products, but I have a hard time making a query that works. class Transaction(models.Model): ... transaction_type = models.PositiveIntegerField(choices=TYPE_CHOICES, db_index=True) date = models.DateTimeField(auto_now_add=True, db_index=True) comment = models.CharField(max_length=255, blank=True, null=True) status = models.PositiveIntegerField(choices=STATUS_CHOICES, default=1, db_index=True) ... class TransactionItem(models.Model): transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE) product = models.ForeignKey(product, on_delete=models.CASCADE related_name="product") stock_location = models.ForeignKey(warehouse_stock_locations, on_delete=models.CASCADE, verbose_name="Lagerplats", related_name="stock_location", blank=True, null=True) qty = models.IntegerField(default=0, blank=True, null=True) unit_cost = models.DecimalField(max_digits=12, decimal_places=2, blank=True, null=True) so I want to collect the quantities in all transactions that have the status "2", which is equal to a completed inventory count, goods delivery, while status=1 and status=3 are ignored. I'll then sum all qty in TransactionItems and display on the respective product detail pages. I've looked at various examples of queries, but they all lead me to an error. Could you point me in the right direction?