Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django project that collects data in local database installed on cloud system and sync that data in cloud database when internet is available
i want to add a feature to my django project that if the internet is not available the website will use the local database that will be installed on the client system to store data like sales, purchases, etc but as soon as internet is connected it will take all data from local database and store all that data in the cloud database (main database) deleting the data from local database. as i am new to django, i was wondering if someone can point me towards the right direction. -
django ValueError Cannot query "abcd@gmail.com": Must be "object" instance
i am trying to make an app for student but i'm getting this error, as you can see for convenient i wanted to use like that one i showed bellow but it doesn't work, should i keep using like before? or i could use like that ? what would be best way ? ValueError at /student/program_structure/ Cannot query "abcd@gmail.com": Must be "Student" instance. thank you so much :) models.py class Student(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) status = models.CharField(max_length=10, choices=STATUS, default='active') class Program(models.Model): #everything was fine when used user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) #this one #but when using this one i started getting this error from views.py user = models.ForeignKey( Student, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200, unique=True) prefix = models.CharField(max_length=20) views.py class Program_structure(generic.View): def get(self, *args, **kwargs): profile = Student.objects.all() program_structure = Course.objects.filter(user=self.request.user) context = { 'test':program_structure, 'profile':profile, } return render(self.request, 'program_structure.html', context) -
How to set password for social login signup after changing email django-allauth
I am trying to come up with a solution to this problem that I am facing however, I cannot seem to find it. Assume a scenario where the user logs into the django website using their Google Gmail account. After logging in the user decided to change the default email from test@gmail.com to one of their other email at test@test.com. The user goes to accounts/emails/ and adds a new account, verifies the account set's it at primary and deletes the old email test@gmail . I have written an adapter that would link users to their social login if a user already exists so if they login using the Google account test@gamil.com they will still be redirected to the same user. However, I want to give the user a page to set a password for test@test.com in case the user wanted to use forget password option in order to sign in locally. How can I redirect users after deleting their social login email to set a new password for the new email? -
Many to many fields in widget form
I have problem with display many to many field in form widget. Category is not display in template. Title is ok (is display) but category isn't - category is empty. What can I do to display many to many fields in my template form with multiplechoice checkboxes? Why I cant display article categories in widget form? MODELS.py article model: class Article(Created, HitCountMixin): title = models.CharField(max_length=120) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) category = models.ManyToManyField(ArticleCategory, related_name='articles') category model: class ArticleCategory(Created): category_name = models.CharField(max_length=128) slug = models.SlugField(null=False, unique=False) VIEWS: class UpdateArticleView(LoginRequiredMixin, UpdateView): template_name = 'news/update_article.html' form_class = EditArticleForm model = Article def get_success_url(self): pk = self.kwargs["pk"] slug = self.kwargs['slug'] return reverse_lazy("news:article_detail", kwargs={'pk': pk, 'slug': slug}) FORMS.py class AddArticleForm(forms.ModelForm): title = forms.CharField( label="Tytuł", max_length=120, help_text="Tytuł newsa", widget=forms.TextInput(attrs={"class": "form-control form-control-lg pr-5 shadow p-1 mb-1 bg-white rounded"}), required=True, ) category = forms.MultipleChoiceField( widget=forms.CheckboxSelectMultiple, ) And in my HTML TEMPLATE: <form method="post" enctype='multipart/form-data'> {% csrf_token %} {{ form.media }} {# {% crispy form %}#} {{ form|crispy }} <button type="submit" class="btn btn-outline-primary">EDYTUJ NEWS</button> </form> -
Django model filefield -> upload file from one server to another
I am trying to upload the content of FileField field to 3rd party server but i am getting empty binary at 3rd party server end. Suppose i have FileManager table which has file as a coloumn Model schema: class FileManager(models.Model): file = models.FileField(upload_to=file_input_path) .... Now suppose i have this below function which is getting some particular row from file_manager table and uploading that particular file to some 3rd party service as: def some_task(): some_file = FileManager.objects.get(id=some_id) some_file.file.name = "Some Random custom name" form_data = { "file": some_file.file, } print(form_data['file'].read()) # it is printing empty binary b'' requests.post("xyz.com/process_file", files=form_data) #3rd party service class def process_file(request): data = request.FILES['file'] print(data.read()) #Getting empty binary as-> b'' print(data.name) #printing correct name -> some_file.xlsx How can i access the content of FileField field? Currently i am using FileField.file to access this but while reading its content, it shows empty binary b'' -
How to use async await to get the https response from the request.post in django views?
I have built the project with Django and React. the part of one of API view is looking like follows: data = {"userId": str(email), "answers1": answers1, "answers2": answers2, "words": words} # To get the score from the api using the prepared data score = requests.post(api_url, headers=headers, data=json.dumps(data)) res = [] for s in score: mid = s.decode('utf-8') res.append(json.loads(mid)) result = AnalysisResult.objects.get(user=user) result.w_1 = res[0]['graphA']['W'] result.x_1 = res[0]['graphA']['X'] result.y_1 = res[0]['graphA']['Y'] result.z_1 = res[0]['graphA']['Z'] result.w_2 = res[0]['graphB']['W'] result.x_2 = res[0]['graphB']['X'] result.y_2 = res[0]['graphB']['Y'] result.z_2 = res[0]['graphB']['Z'] result.save() return Response({"message": "The result score is stored in database successfully!"}) Here w_1, w_2, ... are the columns of table in the database. In this view, there is a https request(api_url and headers are defined in my code, and they are all correct). I want to return the response of this view just after get the score from the api, and save it in the table. If this description is not enough, please let me know. I will add more information. -
[DRF]: extra field in serializer with related id
I've been trying hard but I can't find a solution for this, maybe you can help me: I have 2 models: consumption and message. The messages have a field "consumption" so I can know the consumption related. Now I'm using DRF to get all the consumptions but I need all the messages related with them This is my serializers.py file: class ConsumptionSapSerializer(serializers.HyperlinkedModelSerializer): client = ClientSerializer(many=False, read_only=True, allow_null=True) call = CallSerializer(many=False, read_only=True, allow_null=True) course = CourseSerializer(many=False, read_only=True, allow_null=True) provider = ProviderSerializer(many=False, read_only=True, allow_null=True) # messages = this is where I failed class Meta: model = Consumption fields = [ "id", "client", "course", "provider", "user_code", "user_name", "access_date", "call", "speciality_code", "expedient", "action_number", "group_number", "start_date", "end_date", "billable", "added_time", "next_month", "status", "incidented", "messages" ] class MessageSapSerializer(serializers.ModelSerializer): user = UserSerializer(allow_null=True) class Meta: model = Message fields = [ "user", "date", "content", "read", "deleted" ] I have read here Django REST Framework: adding additional field to ModelSerializer that I can make a method but I don't have the consumption ID to get all the messages related. Any clue? -
Use same template with different data on links created in another template
I am facing problem using urls created in the for loop of template file(URL patching). The views file consist of following functions def home(request): data = request.FILES['file'] # i got the data request.session['data'] = data # able to store data so that i can manipulate data ''' data is dictionary suppose data ={'a': [2,3,4], 'b':[4,3,2], 'c':['6,7,3]} ''' members = data.items() return render(request, 'home.html', {'members': members}) to plot data extracted from the sessions data another def plot_graph(request): data = request.session['data'] selected_data = data['a'] # suppose i click on link 'a' link return render(request, 'graph.html', {'selected_data': selected_data}) plotting data with chartjs so that template is graph.html (Its working fine for me) var myLineChart = new Chart(ctx, { type: 'line', data: selected_data, options: options }); home.html {% for member in members %} <tr> <td><a href="{% url "my_app:plot_graph"%}">{{member}}</a></td> </tr> {% endfor %} my_app/urls.py urlpatterns = [ path('', views.home, name='GroupChat'), path('<str:name>/', views.plot_graph, name='plot_graph') ] Here i am missing how to map urls from plot_graph to url patterns, I tried different sources to solve this but none of them helped me, in short my problem is to create links('a', 'b', 'c'..) if you click any link that should display in new page with data associated with … -
IntegrityError when creating a new model object
I'm getting the error: IntegrityError at evaluation/evaluee/new Null value in column "Evaluation_data_id" violates not-null constraint I think it has to do with the way I set up the relationship with the two models. The ideia is: every time one EvaluationModel is created, an EvaluatorModel object should be created too (getting some values such as evaluee and evaluator) from the first model. I created an evaluation_data field so that I could access EvaluationModel Thanks in advance! My model: class EvaluationModel(models.Model): evaluee = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, related_name= '+', verbose_name='Evaluee', ) evaluator = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, related_name= '+', verbose_name='Evaluator', ) dgl = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, related_name= '+', verbose_name='DGL', ) promotion_window = models.BooleanField(default=False, verbose_name = "") currentrole = models.CharField(max_length=50, choices=ROLES, default=None, null = True, blank = True, verbose_name="") promotionrole = models.CharField(max_length=50, choices=ROLES, default=None, null = True, blank = True, verbose_name="") tenure = models.CharField(max_length=50, default=None, null = True, blank = True, verbose_name="Tenure") adjustedtenure = models.CharField(max_length=50, default=None, null = True, blank = True, verbose_name="") pinputlimitdate = models.DateField(null = True, blank = True, verbose_name='', help_text="Format: <em>MM/DD/YYYY</em>.") exposurelistlimdate = models.DateField(null = True, blank = True, verbose_name='', help_text="Format: <em>MM/DD/YYYY</em>.") evaluatorlimitdate = models.DateField(null = True, blank = True, verbose_name='', help_text="Format: <em>MM/DD/YYYY</em>.") shared_with_PM = models.BooleanField("", default=False) shared_with_DGL = models.BooleanField(default=False) shared_with_Evaluator = … -
psycopg2 connect error: cannot pass more than 100 arguments to a function?
I am trying to pass json object as argument to my stored procedure. i tried many things and solved couple of error atlast I am stuck with this erro "psycopg2 connect error: cannot pass more than 100 arguments to a function" i tried json.dumps where it gives me this .. if i am executing from scripts with same input it works fine. below is my stored procedure.. CREATE OR REPLACE PROCEDURE public.insert_usr_details_in_all_tables (jsonobject json) LANGUAGE 'plpgsql' AS $BODY$ DECLARE skill_s Text[] := '{}'; selectedSkill TEXT; edu TEXT; email TEXT; phone TEXT; usr_name TEXT; clg TEXT; lstEmployer TEXT; gendr TEXT; skill_row_count INTEGER; usr_id INTEGER; skl_id INTEGER; intEmailExist INTEGER; expen DECIMAL; BEGIN -- Getting name SELECT jsonobject->'Name' into usr_name; -- Getting education SELECT jsonobject->'Education' into edu; -- Getting phone number SELECT jsonobject->'phone_number' into phone; -- Getting experience SELECT (jsonobject->>'Exp')::DECIMAL INTO expen; --Getting college SELECT jsonobject->'College' into clg; -- Getting last employer SELECT jsonobject->'CurrentEmployer' into lstEmployer; --Getting gender SELECT jsonobject->'Gender' into gendr; -- Getting Email SELECT json_array_length(jsonobject->'Email') into intEmailExist; IF intEmailExist > 0 THEN email:=array(SELECT json_array_elements_text(jsonobject->'Email')); END IF; -- Insert user details in 'Extractor_usr_details' table. INSERT INTO public."Extractor_usr_details"(name, phone_number, email, exp, education, college, "currentEmployer", gender)VALUES ( usr_name, phone, email, expen, edu, clg, lstEmployer, … -
Django project setup issue with the command : django-admin startproject xxxxxx
I started coding in python - Django just few days ago .I am using windows 10 . I installed Django project with pip and virtual env. but when I give this command : django-admin startproject xxxxxx the console is showing : Command not found: django-admin.py Please help me to solve the issue. -
Error of Django NoReverseMatch at /top/ although being designated name of url
I got an error NoReverseMatch at /top/ and I cannot fix it. I got an error like Reverse for 'create_users' not found. 'create_users' is not a valid view function or pattern name. My application structure is login -urls.py -views.py app -urls.py -views.py -settings.py templates -app -top.html -users -login.html users -urls.py -views.py I wrote code urls.py of login from django.urls import path, include from . import views urlpatterns = [ path('login/', include('registration.urls')), path('create_users/', views.Create_users.as_view(), name="create_users"), ] I wrote code views.py of login class Create_users(CreateView): def post(self, request, *args, **kwargs): form = UserCreateForm(data=request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('user_id') password = form.cleaned_data.get('password1') user = authenticate(username=username, password=password) login(request, user) return redirect('/') return render(request, 'create.html', {'form': form,}) def get(self, request, *args, **kwargs): form = UserCreateForm(request.POST) return render(request, 'create.html', {'form': form,}) create_users = Create_users.as_view() Furthermore I wrote code in templates/app/top.html <html lang="ja"> <body> {% if user.user_id %} <p>Hello,{{ user.user_id }}</p> {% else %} <a href="{% url 'users_index' %}">Click here</a> <a href="{% url 'create_users' %}">Create user</a> {% endif %} </body> </html> I rewote templates/app/top.html,I added app_name="login" in urls.py of login like <a href="{% url 'login:create_users' %}">Create user</a> but another error happens. I designated name of url,but NoReverseMatch error happens. What is wrong in my code? -
Apache, mod-wsgi: Any URL is served by project, ServerName is ignored
I am setting up a Django project and Apache on Ubuntu 20. The below setup correctly displays the Django project, however ANY URL that points to the server's IP address is served this project. I obviously need to limit this to my particular website mysite.com. ServerName is ignored. I have looked at other question/answers. However, they usually mention httpd.conf, which is no longer used in Apache. Or, there is no accepted answer. Or, it just isn't relevant to my setup. Also, I've been told not to touch apache2.conf. This is a brand-new installation instance so no weird stuff hanging around. I will eventually need to have multiple sites served on the same server. Install Apache mod-wsgi: sudo apt install apache2 apache2-utils ssl-cert libapache2-mod-wsgi sudo a2enmod rewrite sudo systemctl restart apache2 Set up .conf file and activate it: Copy mysite.com.conf to /etc/apache2/sites-available sudo a2ensite mysite.com.conf sudo a2dissite 000-default.conf sudo systemctl reload apache2 sudo systemctl restart apache2 mysite.com.conf: <VirtualHost *:80> WSGIApplicationGroup %{GLOBAL} WSGIDaemonProcess test_project_ns processes=1 threads=10 python-path=/home/ubuntu/test_project python-home=/home/ubuntu/test_project/test_env WSGIProcessGroup test_project_ns ServerAdmin webmaster@localhost DocumentRoot /var/www/html ServerName mysite.com ServerAlias www.mysite.com ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined <Directory /home/ubuntu/test_project/test_ui> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/ubuntu/test_project/test_ui/wsgi.py </VirtualHost> Result: mysite.com correctly serves up the … -
I want to use css styling in pycharm using django framework
I want to use css styling in pycharm using django framework. On running it, no error occurs but it also does not show any of the styling being done. Does pycharm support css stylesheet? here is my code: style.css : body{ background: pink url("images/background.png"); } index.html : {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'music/style.css' %}" /> {% if all_albums %} <h3>here are all my albums:</h3> <ul> {% for album in all_albums %} <li><a href = "{% url 'music:detail' album.id %}"> {{ album.album_title }}</a></li> {% endfor %} </ul> {% else %} <h3>You don't have any Albums</h3> {% endif %} detail.html : <img src="{{ album.album_logo }}"> <h1>{{ album.album_title }}</h1> <h2>{{ album.artist }}</h2> {% if error_message %} <p><strong>{{ error_message }}</strong></p> {% endif %} <form action="{% url 'music:favorite' album.id %}" method="post"> {% csrf_token %} {% for song in album.song_set.all %} <input type="radio" id="song{{ forloop.counter }}" name="song" value="{{ song.id }}"> <label for="song{{ forloop.counter }}"> {{ song.song_title }} {% if song.is_favorite %} <img src="#"/> {% endif %} </label><br> {% endfor %} <input type="submit" value="Favorite"> </form> -
Mock class attribute with side_efffect
How can I raise exceptions while accessing an attribute of the mocked object? I have tried to do the same with the following snippet, import unittest from unittest import TestCase from django.core.exceptions import ObjectDoesNotExist from unittest.mock import MagicMock, PropertyMock def function_to_call_one_to_one(model_instance): try: return model_instance.artist.name except ObjectDoesNotExist: # calling `model_instance.artist` will raise `ObjectDoesNotExist` exception return "raised `ObjectDoesNotExist`" class TestObjectDoesNotExist(TestCase): def test_artist_name(self): model_instance = MagicMock() model_instance.artist.name = "Michael Jackson" name = function_to_call_one_to_one(model_instance) self.assertEqual(name, "Michael Jackson") def test_artist_name_with_error(self): model_instance = MagicMock() model_instance.artist = PropertyMock(side_effect=ObjectDoesNotExist) res = function_to_call_one_to_one(model_instance) self.assertEqual(res, "raised `ObjectDoesNotExist`") if __name__ == '__main__': unittest.main() Unfortunately, the test function, test_artist_name_with_error(...) has failed with message, AssertionError: <MagicMock name='mock.artist.name' id='140084482479440'> != 'raised ObjectDoesNotExist' How can I write the unit-test for this case? Note: I have seen this SO post, Python: Mock side_effect on object attribute, but, it doesn't work for me. I hope, this example is a reproducible one. -
Using AJAX with a Django MultipleChoiceField with multiple checkboxes
I'm sending the data from a form with MultipleChoiceField via AJAX and in the template I have multiple checkboxes. I am having problems sending the selected checkboxes. My first attempt was this: var selected =[]; $('.checkboxes:checked').each(function(){ selected.push($(this).val()) }); and then in $.ajax: data: { email : $('[name=email]').val(), country: $('[name=country]').val(), category: selected, but this didn't work. After this I tried to send in the selected values as a string and then just split them and create a list in the view. I managed to do that but I now can't figure out on how to replace the value of the field in the form. form = SubscriberForm(request.POST) categories = form['category'].value() category = categories[0].split(',') del category[-1] form.instance.category = category I'm not sure as to why this doesn't work. I even tried setting a dummy string just to see if the problem was with my category variable but that didn't work either. -
Column core_event.hometask does not exist
When I run my Django project on production server, I have this error: ProgrammingError at /admin/core/event/ column core_event.hometask does not exist LINE 1: ..._event"."is_approved", "core_event"."event_type", "core_even... What I should do to fix it? Now I haven't "hometask" field in my model: class Event(models.Model): name = models.CharField(max_length=100, null=True) author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) description = models.TextField(max_length=1000, blank=True, null=True) date_start = models.DateTimeField(null=True, blank=True) date_finish = models.DateTimeField(null=True, blank=True) image = models.ImageField( upload_to="event_images/", default='event_images/default.png', blank=True, null=True) is_approved = models.BooleanField(null=True) TYPE_CHOICES = ( ('Event', "Мероприятие"), ('Lesson', "Урок"), ) event_type = models.CharField(choices=TYPE_CHOICES, max_length=200, default="Мероприятие") topics = ArrayField(models.CharField(max_length=200), blank=True, null=True) materials = ArrayField(models.URLField(), blank=True, null=True) possible_users = models.ManyToManyField("core.User", blank=True, related_name='possible_users') actual_users = models.ManyToManyField("core.User", blank=True, related_name='actual_users') classes = models.ManyToManyField("core.Class", blank=True, related_name='classes') -
Django - ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine
i have a really trange problem, when i run my django server, even the simplest one it calls this error once every like 1 minute. ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine. The thing is, nothing is breaking. Server is running fine. I've tried to trun off firewall but it didnt help and also when i turned off my antivirus program, it still makes this error. I have newest version of python and django installed. Does anybody know how to fix this? I've searched for over one day for this problem solution, but i didnt find anything helpful. -
Passing HTML tags with Python
i'm currently working on a proyect that involve "markdown2" librarie to transform .MD files to HTML tags. Almost everything works, but when i render HTML file in python and throw the content of .MD file converted, it just shows the literal tags. Here is the function that converts MD files to HTML tags: def get_entry(title): try: f = default_storage.open(f"entries/{title}.md") return f.read().decode("utf-8") except FileNotFoundError: return None And here is the function that pass those HTML tags and render the HTML file: def entry(request, title): entry = markdown(util.get_entry(title)) return render(request, "encyclopedia/entry.html", { "entry" : entry }) Here is the HTML file: {% extends 'encyclopedia/layout.html' %} {% block title %} {% endblock %} {% block body %} {{ entry }} {% endblock %} In the browser it shows the HTML file withe converted MD files like this: enter image description here ¿How can i pass those HTML tags so the browser understand that they are tags and not strings? -
Filtering a Boolean field
Trying to filter boolean field, but it brings the error :too many values to unpack (expected 2) Here is the code def index(request): if not request.session.has_key('currency'): request.session['currency'] = settings.DEFAULT_CURRENCY setting = Setting.objects.get(pk=1) category = Category.objects.all() products_latest = Product.objects.all().order_by('-id')[:4] # last 4 products products_slider = Product.objects.all().order_by('id')[:4] # first 4 products products_picked = Product.objects.all().order_by('?')[:4] # Random selected 4 products products_promoted = Product.objects.filter('promote=True')[:7] # The error origin class Product(models.Model): title = models.CharField(max_length=150) keywords = models.CharField(max_length=255) promote = models.BooleanField(default=False) description = models.TextField(max_length=255) image = models.ImageField(upload_to='images/', null=False) price = models.DecimalField(max_digits=12, decimal_places=2, default=0) minamount = models.IntegerField(default=3) Why is it bringing the error and how do i fix it ? -
Why is Huey running all historic task all of a sudden?
We have an old setup with older django and huey queue using Redis. Everything was working fine with few minor bumps until now. Huey now decided to rerun all of the historic tasks for no reason as far as I can tell. Here's the config I'm using HUEY = { 'name': 'serafin', 'store_none': True, 'always_eager': False, 'consumer': { 'quiet': True, 'workers': 100, 'worker_type': 'greenlet', 'health_check_interval': 60, }, 'connection': { 'host': 'localhost' if DEBUG else '...cache.amazonaws.com', 'port': 6379 } } Where should I look for reasons? How can this be prevented? -
How to do a translator?
I am currently coding my first website, which is a translator in an invented language. You input a random phrase and it should get translated in the invented language. Here's the code for the translation: class TranslatorView(View): template_name= 'main/translated.html' def get (self, request, phrase, *args, **kwargs): translation = "" for letter in phrase: if letter.lower() in "a": if letter.isupper(): translation = translation + "U" else: translation = translation + "u" elif letter.lower() in "t": if letter.isupper(): translation = translation + "A" else: translation = translation + "a" elif letter.lower() in "c": if letter.isupper(): translation = translation + "G" else: translation = translation + "g" elif letter.lower() in "g": if letter.isupper(): translation = translation + "C" else: translation = translation + "c" return render(request, 'main/translator.html', {'translation': translation}) def post (self, request, *args, **kwargs): self.phrase = request.POST.get('letter') translation = self.phrase context = { 'translation': translation } return render(request,self.template_name, context ) Template where you input the phrase: {% extends "base.html"%} {% block content%} <form action="{% url 'translated' %}" method="post">{% csrf_token %} <div class="form-group"> <center><h2 class = "display-3">TRANSLATE YOUR DNA CHAIN</h2></center> <br> <br> <textarea class="form-control" name='text' id="exampleFormControlTextarea1" rows="6"></textarea> <br> <button type='Submit' class= "btn btn-primary btn-lg btn-block">Translate</button> </div> </form> {% endblock content %} Template where … -
How to Insert HTML code to database using json and django?
I am trying to add HTML template code directly into database in django-rest-framework. And want to use json as retrieve and add the html code. How can I do this? class AddHTML(models.Model): template_name = models.CharField(max_length=50, default="") HTML_code = models.TextField(default="") def __str__(self): return self.template_name serializer.py class AddHTMLSerializer(serializers.ModelSerializer): class Meta: model = AddHTML fields = '__all__' views.py class HTMLData(APIView): def get(self, request, format=None): html = AddHTML.objects.all() serializer = AddHTMLSerializer(html, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = AddHTMLSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class HTMLDataDetail(APIView): def get_object(self, id): try: return AddHTML.objects.get(id=id) except AddHTML.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) def get(self, request, id, format=None): html = self.get_object(id) serializer = AddHTMLSerializer(html) return Response(serializer.data) def put(self, request, id, format=None): html = self.get_object(id) serializer = AddHTMLSerializer(html, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, id, format=None): html = self.get_object(id) html.delete() return Response(status=status.HTTP_204_NO_CONTENT) Here in views what should I do that without loosing any tags of HTML data I could easily save and retrieve from database. Kindly reply soon -
How do deploy GeoDjango wit Postgres using Elastic Beanstalk Application
I am trying to Deploy the GeoDjango Application with Postgres on AWS Elastic Beanstalk. But it get stuck in GDAL on Amazon Linux 2 and Python 3.7. -
Django: Class has no 'objects' member
models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title views.py from django.shortcuts import render from .models import Post def meldungen(request): context = { 'posts': Post.objects.all() } return render(request, 'web/meldungen.html', context) Top: There is the Error in line 4: *Class 'Post' has no 'objects' member - pylint(no-member). I tried to migrate it an the problem wasn't solved. But in the django docs i read: If you don’t add your own Manager, Django will add an attribute objects containing default Manager instance. ( https://docs.djangoproject.com/en/3.0/ref/models/class/ ) I read all StackOverflow Posts for this problem but no solution worked. I (i use VSC) tried installing pylint-django, reinstalled pylint and pip .... But here it looks like there isn't just an linter warning, because on the server (Debug is true) appears this error: Error during template rendering In template C:\(...)\web\templates\web\base.html, error at line 9 int() argument must be a string, a bytes-like object or a number, not'NoneType' In this line: If i comment the error line in the view.py file out the site works without any errors. Also i tried render the …