Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Error during template rendering for crispy forms with dynamic fields : 'int' object has no attribute 'get'
I have been trying to implement dynamic forms with a given number of fields and rendering these with crispy forms. However, the following errors are coming when rendering the page: Template error: In template C:\Users\USER14\Documents\testprep\lib\site-packages\crispy_forms\templates\bootstrap4\errors.html, error at line 1 'int' object has no attribute 'get' 1 : {% if form.non_field_errors %} 2 : <div class="alert alert-block alert-danger"> 3 : {% if form_error_title %}<h4 class="alert-heading">{{ form_error_title }}</h4>{% endif %} 4 : <ul class="m-0"> 5 : {{ form.non_field_errors|unordered_list }} 6 : </ul> 7 : </div> 8 : {% endif %} 9 : Traceback (most recent call last): File "C:\Users\USER14\Documents\testprep\lib\site-packages\django\forms\forms.py", line 304, in non_field_errors return self.errors.get(NON_FIELD_ERRORS, self.error_class(error_class='nonfield')) File "C:\Users\USER14\Documents\testprep\lib\site-packages\django\forms\forms.py", line 170, in errors self.full_clean() File "C:\Users\USER14\Documents\testprep\lib\site-packages\django\forms\forms.py", line 372, in full_clean self._clean_fields() File "C:\Users\USER14\Documents\testprep\lib\site-packages\django\forms\forms.py", line 384, in _clean_fields value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name)) File "C:\Users\USER14\Documents\testprep\lib\site-packages\django\forms\widgets.py", line 657, in value_from_datadict getter = data.get Exception Type: AttributeError at /upload/1/SingleCorrect/10/ Exception Value: 'int' object has no attribute 'get' What exactly prompts this error? Following are the code snippets I am using. views.py: def uploadQP(request,qp,typeofq,numberOfquestion): if request.method == 'POST': form=CreateForm(repetitions=numberOfquestion,data=request.POST,files=request.FILES) if form.is_valid(): if typeofq=='SingleCorrect': for i in range(numberOfquestion): files=SingleIntegerType() files.QuestionPaper=get_object_or_404(QuestionPaper,pk=qp) files.question=request.FILES['question_%d' % i] files.correct_answer=request.POST['correct_answer_%d' % i] files.QuestionNumber=request.POST['question_number_%d' % i] files.save() return redirect('create_q') elif request.method=='GET': form=CreateForm(numberOfquestion) return render(request, 'upload_q.html',{'form':form}) … -
Django Modelform ForeignKey Listing Problem
I have a staff list. I have a model for this as follows. models.py: class NumberOfMealsEaten(models.Model): month = models.ForeignKey(Months, on_delete=models.CASCADE) staff = models.ForeignKey(Staffs, on_delete=models.CASCADE) maelseaten = models.IntegerField("Number of meals eaten", validators=[MinValueValidator(0)], default=0) def __str__(self): return str(self.staff) For these employees, the meal fee is calculated every month according to how many meals each staff has eaten. First, at the beginning, I want to choose "the name of the relevant month" only once. Then I want the staff names from Foreignkey to be automatically listed as "text" in the template, not in the form of a drop-down menu. So I just want the "maelseaten" field filled in for the staff. As an example, the list will look like this: enter image description here In other words, this form will add the number of meals for each staff member for the selected month to the database. Thank you in advance for your attention and help. -
Increment number until it matches another number
I am trying to write an algorithm that will increase portion size until the total_cals are as close to the specified argument calories as possible. Here is my model: class Foods(models.Model): name = models.CharField(max_length=100) calories = models.IntegerField() protein = models.FloatField() carbs = models.FloatField() fat = models.FloatField() sugar = models.FloatField(null=True) fiber = models.FloatField(null=True) amount_in_grams = models.IntegerField(default=100) portion_size_in_grams = models.IntegerField() Here is the function I have: def mealPlanMaker(calories): total_cals = 0 meal = [Foods.objects.get(name='Rice'), Foods.objects.get(name='Broccoli'), Foods.objects.get(name='Chicken') while calories > total_cals: for i in meal: portion_size = i.portion_size_in_grams + 1 total_cals += i.calories * portion_size / 100 meal_dict[i.name] = portion_size meals.append(meal_dict) So what I want to do is increase the portion size until the total_cals is as close as possible to calories, say within a range of 50. But my function doesn't work. -
Django access grandchild instances from grandparent
I have the following models class City(models.Model): name = models.CharField() class Surburb(models.Model): name = models.CharField() city = models.ForeignKey( 'City', related_name='surburbs') class ShoppingMall(models.Model): name = models.CharField() location = models.ForeignKey( 'Location', related_name='shoppingmalls') class Store(model.Model): shoppingmall = models.ForeignKey( 'ShoppingMall', related_name='stores') storetype = models.ForeignKey( 'Storetype', related_name='stores') class Storetype(models.Model): title = models.CharField() #View def index(request): cities = City.objects.all().prefetch_related( 'locations__shoppingmalls__stores') return render(request, 'index.html', {'cities':cities}) #Template {% for city in cities %} {% ifchanged %} <li><a href="#">{{ city }}</a> <ul class="sub-menu"> {% with locations=city.locations.all|dictsort:'name' %} {% for location in locations %} {% ifchanged %} <li><a href="#">{{ surburb.name }} </a> <ul class="sub-menu"> {% with shoppingmalls=surburb.shoppingmalls.all|dictsort:'name' %} {% for shoppingmall in shoppingmalls %} {% ifchanged %} {% with stores=shoppingmall.stores.all|dictsort:'name' %} {% for store in stores %} <li> {% ifchanged %} {{ store.storetype.title }} {% endifchanged %} </li> {% endfor %} {% endwith %} {% endifchanged %} {% endfor %} {% endwith %} </ul> </li> {% endifchanged %} {% endif %} {% endfor %} {% endwith %} </ul> <span class="arrow-main-menu-m"> <i class="fa fa-angle-right" aria-hidden="true"></i> </span> </li> {% endifchanged %} {% endfor %} I have tried many things to get the storetype not to display duplicate storetypes without success. This is because each mall can have the same storetypes from another … -
Django: update not saving date without raising error
I have a view in my Django app where I want to update a queryset´s DateField. It´s quite simple, the field works fine in other views (not a model problem) and it doesn´t raise any error when running the view. The other elements in the view are stored ok. The view @transaction.atomic @login_required def BocetoArmando(request): operaciones = OperacionK.objects.filter(creador__username='this_user', estatus__id=1) operaciones.update( fecha_conf_comercial=date.today(), fecha_conf_admin=date.today(), confirmador_admin=request.user, estatus=EstatusOperacionK.objects.get(estatus__icontains="Armando")) lista = [x.id for x in operaciones] pedidos = PedidosK.objects.filter(comprobante__in=lista) pedidos.update(fecha_conf_comercial=datetime.datetime.today()) for pedido in pedidos: producto = ProductosBase.objects.get(pk=pedido.producto.id) producto.existencias = producto.existencias - pedido.uds producto.existencias_bloqueada = producto.existencias_bloqueada - pedido.uds producto.save(update_fields={'existencias', 'existencias_bloqueada'}) return DispatchManager(request) I tried both options with the same result: pedidos.update(fecha_conf_comercial=datetime.datetime.today()) pedidos.update(fecha_conf_comercial=date.today()) If I run pedidos.update(fecha_conf_comercial=date.today()) in Django´s shell it´s updated correctly. This is part of a big app that handles this datefield without any problems in the rest of the views. I can´t figure out what is happening here. Any clues welcome. Thanks in advance! -
How to have django-admin recognized in Eclipse/LiClipse?
I've been trying to execute django-admin from within a LiClipse project using: projectName = "someProject" command = 'django-admin startproject ' + projectName process = subprocess.Popen(command.split(), stdout=subprocess.PIPE) and also subprocess.check_call(shlex.split(command)) But each time I get the error: FileNotFoundError: [Errno 2] No such file or directory: 'django-admin' However, when I run the same program from the Linux terminal using python3 main.py, it works fine. So I figured it might be because django-admin's path isn't added to PYTHONPATH. I did a locate "django-admin" to find these paths: /home/nav/.pyenv/shims/django-admin /home/nav/.pyenv/shims/django-admin.py /home/nav/.pyenv/versions/3.8.7/bin/django-admin /home/nav/.pyenv/versions/3.8.7/bin/django-admin.py /home/nav/.pyenv/versions/3.8.7/bin/__pycache__/django-admin.cpython-38.pyc /home/nav/.pyenv/versions/3.8.7/lib/python3.8/site-packages/django/bin/django-admin.py /home/nav/.pyenv/versions/3.8.7/lib/python3.8/site-packages/django/bin/__pycache__/django-admin.cpython-38.pyc and added it to PYTHONPATH... ...but I get the same error when I run the program from within LiClipse. Does anyone know why this problem is happening and how it can be fixed? -
How to disconnect channel from group using custom key only?
Good day! I writing chat according on django-channels official guide. In my connection to the group, I have instance of my custom Django model named Player. How I can disconnect channel to chat group, if I know only pk of Player, which need to be banned? class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.player = await sync_to_async(Player.objects.get, thread_sensitive=True)(account=self.scope["user"]) self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'id': self.player.pk, 'nickname': self.player.nickname, 'image': self.player.image.url, 'message': message } ) # Receive message from room group async def chat_message(self, event): message = event['message'] id = event['id'] nickname = event['nickname'] image = event['image'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message, 'time': datetime.now().time().strftime("%H:%M"), 'id': id, 'nickname': nickname, 'image': image, })) -
no such table: django_session On azure web app
Im trying to deploy a django app through azure web app service, Im choosing Postgress db for the deployment, However i have prepared my settings for the pg db, like so DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME':'..' , 'USER': '...', 'PASSWORD': '..', 'HOST': '....', 'PORT':'...', } } I have deleted all the migrations/__pycache__ files, db.sqlite3 And then I did manage.py makemigrations AppName followed by manage.py migrate AppName , The migrations are done, and i can see all the tables created to the PgAdmin. But there is weird stuff going, every time i delete db.sqlite3, its created again after i finish migrate even with the settings where there is no sqlite3 mentioned. I tried to find a solution for this issue but seems im out of tricks. any help would be so appreciated. -
how to use get_context_data in django ListView(three class model)
I have three class models. A contains the Academy's class name, B contains the student name, and refers to A (class name) as an foreign value. C contains the date the student enrolled in the academy and refers to B (student) as an outpatient value. Set Academy as the object of get_context_data and return the for statement to output the entire class anem of academy in the first field of the table. This is a problem that I am not solving from here. I would like to output the number of students who satisfy a specific condition for each class name. <table> {% for academy in academies %} <tr class="text-center"> <td>{{ academy.academy_class_name }}</td> <td>{{ i want to count }}</td> ----- problem </tr> {% endfor %} </table> class ListView(ListView): model = Academy context_object_name = 'academies' template_name = 'list.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['to_date'] = self.request.GET.get('to_date') context['from_date'] = self.request.GET.get('from_date') context['option_radio'] = self.request.GET.get('optionRadios') if context['option_radio'] == 'period': context['student'] = Student.objects.filter(academy_id=self.id) ----- I want to load the class name of each academy being returned by the for statement. context['screening'] = Attribute.objects.filter( entry_date__lte=context['to_date'], entry_date__gte=context['from_date'], student_id__in=context['student'] ).count() return context -
load multuple dummy data dinago for windows
I have this script python manage.py loaddata ./project_apps/*/fixtures/test/*.json It works perfectly on linux. This scrip says 'take all dirs from /project_apps, in every dirs, if there is fixtures folder take it and than search for /test dir, if there is take it and grab all files there which have .json extension'. That is fine, but when i run the same command on windows python manage.py loaddata .\project_apps\*\fixtures\test\*.json it throws me an error: there is no fixtures with that '*' name If i pass the absolute path to the file which a want. It is ok. The windows finds it. So is there an analogous command for windows, to can grab all files i want at once. -
import Django Conventional structure
hello, im new with django, how can I create standard structure of django in Pycharm as I create new django project in python there is no such a file like apps.py or models.py please help me how can I import all those standard files to project (sorry if it is stupid question) -
Django costume save form cant save in user id field
please someone help me i have form costum save to crop and save but cannt crop and also cannt save in user field in db its all in edit profile to edit profile name and photo its separate model for profile picture bcs i dont know how to save with name and profile info thanks so much NOT NULL constraint failed: authy_photo.user_id models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') name = models.CharField(max_length=50, null=True, blank=True , default='') profile_info = models.TextField(max_length=150, null=True, blank=True, default='') created = models.DateField(auto_now_add=True) favorites = models.ManyToManyField(Post) def __str__(self): return self.user.username class Photo(models.Model): picture = models.ImageField(upload_to=user_directory_path,blank=True, null=True, verbose_name='photos') uploaded_at = models.DateTimeField(auto_now=True) user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='photo') class Meta: verbose_name = 'photo' verbose_name_plural = 'photos' forms.py class PhotoForm(forms.ModelForm): x = forms.FloatField(widget=forms.HiddenInput()) y = forms.FloatField(widget=forms.HiddenInput()) width = forms.FloatField(widget=forms.HiddenInput()) height = forms.FloatField(widget=forms.HiddenInput()) class Meta: model = Photo fields = ('picture', 'x', 'y', 'width', 'height',) def save(self, *args, **kwargs): photo = super(PhotoForm,self).save() self.instance.user_id = user x = self.cleaned_data.get('x') y = self.cleaned_data.get('y') w = self.cleaned_data.get('width') h = self.cleaned_data.get('height') image = Image.open(photo.picture) cropped_image = image.crop((x, y, w+x, h+y)) resized_image = cropped_image.resize((200, 200), Image.ANTIALIAS) resized_image.save(photo.picture.path) return photo class EditProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('name', 'profile_info') and one view views.py @login_required def EditProfile(request): … -
mannual authentication system in django
views.py i am trying to get user and check if it is verified then login otherwise submit otp and do verify. but i can't get user and on otp page i got error. please tell me how to do better this code def login(request,pk): if request.method == 'POST': get_otp = request.POST.get('otp') get_user = request.POST.get('useremail') print(get_user) if get_otp: usr = Customer.objects.get(email=get_user) if int(get_otp) == Customer.objects.filter(email=usr).last().otp: usr.is_active = True usr.is_verified = True usr.save() messages.success( request, 'Your account is successfully verified') return render(request, "index.html") else: messages.error(request, "Otp is wrong") return render(request, "authentication/register.html", {'otp':True , 'user':usr}) email = request.POST['em'] password = request.POST['ps'] user_id = Customer.objects.get(id=pk) user = Customer.objects.filter(email=email) print(user) if len(user) > 0: if user[0].is_verified and user[0].password == password: request.session['firstname'] = user[0].firstname request.session['lastname'] = user[0].lastname request.session['email'] = user[0].email request.session['phone'] = user[0].phone_no request.session['id'] = user[0].id return redirect('index') elif user[0].password != password: messages.error( request, 'Please enter correct password') return render(request, "authentication/login.html") elif not user[0].is_active: messages.info(request, "Please varify your account") user_otp = random.randint(100000, 999999) user[0].otp = user_otp user[0].save() subject = f"Welcome to DV creation" message = f"Hi {user[0].email} , Your OTP for varificaion is {user_otp} , (Note: OTP is only for 5 min)" email_from = settings.EMAIL_HOST_USER recipient_list = [user[0].email, ] send_mail(subject, message, email_from, recipient_list) return render(request, "authentication/register.html", … -
Trying to access existing mySql table with data but I get typeerror: not enough arguments for format string
I connected my database correctly in my settings.py. I created models via inspectdb for my already existing tables, I migrated them, but when I try to access them through the administration panel I get this error. What should I do? django: v3.2 python: v3.7.9 mySql: v8.0.19 -
How can deduct the value from table in django
I am trying to deduct the value of a column in a table from another table. I want if there is any issue in any item it deduct the from the other table but when i do it show the error failed 'ForwardManyToOneDescriptor' object has no attribute 'orderProduct' View.py from purchase.models import OrderRequest from .models import GatePass class OrderView(TemplateView): template_name = 'inventory/orderCheck.html' def get(self, request, *args, **kwargs): orderId = self.request.GET.get('order') order = OrderRequest.objects.filter(pk=orderId) args = {'order': order} return render(request, self.template_name, args) def post(self, request): orderId = self.request.GET.get('order_id') statusAccept = self.request.POST.get('action') == "accept" statusReject = self.request.POST.get('action') == "reject" if statusReject: try: data = self.request.POST.get orderView = GatePass( fault=data('fault'), remarks=data('remarks'), order_id=orderId ) order = OrderRequest.order.orderProduct.quantity - orderView.fault order.save() orderView.save() return redirect('gatePass', 200) except Exception as e: return HttpResponse('failed {}'.format(e), 500) -
Django models for an ESL school
I am working on building a management interface for an ESL (English as a Second Language) institute, basically it is a language school where people learn English. I have prepared my models for each app and I really would like someone to review them and provide me with suggestions and possible mistakes in the design. the models for an app called ez_core: GENDER_CHOICES = [ ('Female', 'Female'), ('Male', 'Male') ] STREET_ADDRESS_CHOICES = [ ('A', 'A'), ('B', 'B') ] EDUCATIONAL_LEVEL_CHOICES = [ ('Bachelor\'s Degree', 'Bachelor\'s Degree'), ('Master\'s Degree', 'Master\'s Degree'), ('PhD Degree', 'PhD Degree'), ] CONTACT_RELATIONSHIP_CHOICES = [ ('Brother', 'Brother'), ('Father', 'Father'), ('Mother', 'Mother'), ('Sister', 'Sister'), ('Uncle', 'Uncle'), ('Wife', 'Wife'), ] MEDICAL_CONDITION_CHOICES = [ ('Chronic Disease', 'Chronic Disease'), ('Allergies', 'Allergies') ] class PersonalInfo(models.Model): full_name = models.CharField(max_length=100) phone_number = models.CharField(max_length=100) email_address = models.EmailField(max_length=100) birthdate = models.DateField() gender = models.CharField(max_length=6, choices=GENDER_CHOICES) personal_id_number = models.CharField(max_length=100) passport_number = models.CharField(max_length=100) personal_photo_link = models.CharField(max_length=100) id_card_attchment_link = models.CharField(max_length=100) passport_attachment_link = models.CharField(max_length=100) street_address = models.CharField( max_length=100, choices=STREET_ADDRESS_CHOICES) address_reference_point = models.CharField(max_length=100) educational_level = models.CharField( max_length=100, choices=EDUCATIONAL_LEVEL_CHOICES) specialization = models.CharField(max_length=100) contact_phone_number = models.CharField(max_length=100) contact_name = models.CharField(max_length=100) contact_relationship = models.CharField( max_length=100, choices=CONTACT_RELATIONSHIP_CHOICES) medical_condition = models.CharField( max_length=100, choices=MEDICAL_CONDITION_CHOICES) medication = models.CharField(max_length=100) class Meta: abstract = True The models for an app called ez_course: … -
Problem in importing the static files in the django?
i project a folder name = portfolio_projects in which i created the app enter image description here here is where my static folder and app is present enter image description here code of my settings.py STATIC_URL = '/static/' STATICFILES_URL=[ os.path.join(BASE_DIR, 'static'), ] and here is the file in which I want to import {% load static %} <link rel="stylesheet" type="text/css" href='{% static "main.css" %}'> here is the screenshot from the editor with marking enter image description here i am getting this error enter image description here -
DRF simpleJWT - Is there anyway to fetch user's data from an access-token with no access to the 'request' param?
I'm trying to write a custom authentication middleware for Django channels since I'm using JWT for my app's authentication scheme. I'm using the method that is mentioned in this article which basically gets user's token in the first request that is made to the websockets and then, in the receive method of the consumers.py file, fetches user's data based on that and then pours it in the self.scope['user'] (can't make use of the token_auth.py method because the UI app is separate..). Now since I have NO ACCESS to the request param that is usually being used in the views.py files to get the user's data, is there anyway to get the user's data out of an access token alone?? -
django-simple-history - Filter model as of a date
I'm trying to filter an Employee model based on their business, but to keep statistics accurate I want to be able to also get all of the employees as of a specific date. Using django-simple-history I can do Employee.history.as_of(date) which returns a generator object with the employees as of that date. Is there a way that I can use the as_of() method in conjunction with djangos object filtering? I could loop through the generator and do the check within that, but I imagine that would be inefficient. -
ModuleNotFoundError: No module named 'MyApp.urls' Traceback (most recent call last):
This Is My Views.py File from django.shortcuts import render def index(request): message = {"message": "I am from url mapping help!"} return render(request, 'MyApp/help.html', context=message) def second_index(request): message = {"message": "Hey Hello!"} return render(request, 'MyApp/index.html', context=message) This Is My admin urls.py file from django.contrib import admin from django.urls import path, include from MyApp import views urlpatterns = [ path('', views.second_index, name="App"), path('/help', include('MyApp.urls')), path('admin/', admin.site.urls), ] This is my app urls.y file from django.urls import path from MyApp import views urlpatterns = [ path('', views.index, name="index"), ] I already added my app to installed _app list INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'MyApp' ] When I run code then this File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'MyApp.urls' Traceback (most recent call last): File "C:\Users\asus\anaconda3\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\asus\anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "C:\Users\asus\anaconda3\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\asus\anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 95, in handle self.run(**options) File "C:\Users\asus\anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 102, in run autoreload.run_with_reloader(self.inner_run, **options) File "C:\Users\asus\anaconda3\lib\site-packages\django\utils\autoreload.py", line 598, in run_with_reloader start_django(reloader, main_func, *args, **kwargs) File "C:\Users\asus\anaconda3\lib\site-packages\django\utils\autoreload.py", line 583, in start_django reloader.run(django_main_thread) File "C:\Users\asus\anaconda3\lib\site-packages\django\utils\autoreload.py", line 301, in run self.run_loop() File "C:\Users\asus\anaconda3\lib\site-packages\django\utils\autoreload.py", line 307, in run_loop … -
How to use JsonField instead of many to many field in django
Let say i have two models like these, and i want to store multiple Book's title in the Author's books. but i do not want to use ManyToManyField, and i want to use json instead class Book(models.Model): title = models.CharField(max_length=100) class Author(models.Model): books = JsonField() How can i get the data(title) in the json format from book and store that in Author(books) based on what the user select in django admin panel.(Actually i want to select the books my self, like i do in the many to many field) -
Multiple database in same MySql Server
I already have and database in MySql for my one Django project. !includedir /etc/mysql/conf.d/ !includedir /etc/mysql/mysql.conf.d/ [client] database = project1 user = project_user password = Password port = 3307 default-character-set = utf8 Here, can i have different database(database=project2) for my second project? Note: I am willing to use same user and same password How can i do that? Thanks in advanced. -
How to print OKM tree model in django?
I have to create an OKM model, and for each sentence when a parsed tree is generated have to print that on a Web UI. I am not getting how to do so in Django! How to print an OKM tree model in the Django interface? In python, I wrote the result.draw(), but how to do draw the same in Django? from django.shortcuts import render import os import stanza from bs4 import BeautifulSoup as bs import re import nltk from nltk.tag import tnt from nltk.corpus import indian def indexView(request): if request.method == "POST": user_string =request .POST.get("user_text") train_data = indian.tagged_sents('hindi.pos') tnt_pos_tagger = tnt.TnT() tnt_pos_tagger.train(train_data) tokens = nltk.word_tokenize(user_string) print(tokens) tag = nltk.pos_tag(tokens) print(tag) grammar = "NP: {<DT>?<JJ>*<NN>}" cp =nltk.RegexpParser(grammar) result = cp.parse(tag) result.draw() context = { 'converted_string': result, 'user_string': user_string, } return render(request,'index.html',context) else: return render(request,'index.html',{'content':""}) def dashboardView(request): return render(request,'dashboard.html') } -
How to get an object after been created using CreateView inside django CBV
am trying to create a notification system that tracks all the activities of my users. to achieve this I have created two models, The Contribution model and Notifition model class Contribution(models.Model): slug = models.SlugField(unique=True, blank=True, null=True) user = models.ForeignKey(User, on_delete=models.PROTECT) amount = models.DecimalField(default=0.00, max_digits=6, decimal_places=2) zanaco_id = models.CharField(max_length=20, blank=True, unique=True, null=True) class Notification(models.Model): slug = models.SlugField(unique=True, blank=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') message = models.TextField(null=True) I want to create a Notification object each time a user creates an object in the Contribution table, but am having some difficulties in getting the object created from CreateView class ContributionAdd(CreateView): model = Contribution fields = ['user', 'amount', 'zanaco_id'] template_name = 'contribution_add.html' def form_valid(self, form, *args, **kwargs): activity_ct = ContentType.objects.get_for_model("????") Notification.objects.create(content_type=activity_ct, object_id="?????",content_object=???,) return super().form_valid(form) how can I achieve the task above ? is their a way doing this using mixins ? -
How to load article page of a blog site using django?
I want to create a blog site. I already created the homepage of the site and there is 4 articles on my blog site. I want to open an article by clicking on it and it will redirect me to the unique article page. Every article page has few images and headlines and line breakers. How will I upload these to my blog model using django? Example article page...See the article page's picture