Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to change field type and retain choices defined in model django 3.0
I am new to Django, I am trying to change field type by retaining choices defined in model. this is my model class MyModel(models.Model): class Type(models.IntegerChoices): INDIRECT= 0 DIRECT = 1 BOTH = 2 name = models.CharField(max_length=20) category = models.IntegerField(choices=Type.choices) price= models.IntegerField() and this is my form class class MyForm(forms.ModelForm): #category = forms.ChoiceField(widget=forms.RadioSelect()) class Meta: model = SPA fields = [ 'name', 'category', 'price' ] I know we can change the field type with the above commented line. but it doesn't bring choices from model.... Please advice how to achieve it. -
django migration on kubernetes replica set
I ran in to a problem, while deploying the django application in kubernetes pod having 3 replicas. Here is the problem: -> I have some db migration to be run in the django application. -> The migration python manage.py migrate --noinput --fake-initial runs during the application startup. -> When I deploy my helm chart having this deployment with 3 replicas, all the 3 replica try to migrate at the same time, the db lock timeout happens. Or some migration fails, saying table already exist. This happens only during the the fresh helm install chart installation, as all pods comes up together. I have not faced this issue while helm upgrade due to rolling update strategy, because only 1 pods comes up and do the migration. My question is: -> Is their any way to tell the kubernetes to bring up replica one-by-one during the helm install just like it do during upgrade. -> Is their any way I can avoid my error through helm hooks, I cannot use helm preinstall (as I need service account and credential to connect to DB) or post install (As the worker thread in django app needs to be rebooted to make migration into effect) -
How can I store a list of model instances in a django model
I am trying to create a form generator in the django admin panel that allows users to create forms graphically by entering the form field name, field ID and field type. How can I go about doing this? I was thinking of creating a model for forms and referencing instances in the model of the whole form. Is this the best way to go about this? Is there a better way? Project is at librebadge.com -
Paginations with ajax and django
Here's the code for the views.py it's a method that receives the "get" request and then retreives the data of the objects after filtering in json format. my views.py @login_required(login_url='login') def filter(request, page=1): """Displays the results of the search for substitute products """ global data # First logic section value = request.GET.get('value') """ logic of seconde user search (get constum search with 3 fields ( grade, categorie, rating)) """ conditions = dict() for filter_key, form_key in (('grade', 'grade'), ('categorie', 'categorie'), ('rating__rating', 'rating')): value = request.GET.get(form_key, None) if value: conditions[filter_key] = value print(conditions) best_product = Product.objects.filter(**conditions) serialize_product = productSerializer(best_product, many=True) print(type(serialize_product.data)) context = { 'best_product': serialize_product.data, } print((context)) return JsonResponse(context) Here is the "query" code that retrieves the data entered (grade, category, rating) then sends it to the view(filter), after processing it retrieves the answer then displays all the objects (in "var html"). My problem is that I want to display just 15 objects at a time (pagination with 15 objects). my scripts.js $('#btn-filter').on('click', function (e) { e.preventDefault(); var grade = $('#grade').val(); var categorie = $('#categorie').val(); var rating = $('#rating').val(); $('#row-after').children().remove(); // alert( 'rating: ' + rating + ' grade: ' + grade+ ' categorie: ' + categorie ); $.ajax({ url: … -
Celery Eventlet Worker django.db.utils.DatabaseError within Docker
I have a web application which is locally run with docker-compose. It contains Django connected to PostgreSQL, Celery and RabbitMQ. Every time I run a shared_task I get the following DatabaseError. worker_1 | [2020-03-17 20:03:40,931: ERROR/MainProcess] Signal handler <bound method DjangoWorkerFixup.on_task_prerun of <celery.fixups.django.DjangoWorkerFixup object at 0x7fa4dbf3ead0>> raised: DatabaseError("DatabaseWrapper objects created in a thread can only be used in that same thread. The object with alias 'default' was created in thread id 140346062341232 and this is thread id 140345963084624.") worker_1 | Traceback (most recent call last): worker_1 | File "/usr/local/lib/python3.7/site-packages/celery/utils/dispatch/signal.py", line 288, in send worker_1 | response = receiver(signal=self, sender=sender, **named) worker_1 | File "/usr/local/lib/python3.7/site-packages/celery/fixups/django.py", line 166, in on_task_prerun worker_1 | self.close_database() worker_1 | File "/usr/local/lib/python3.7/site-packages/celery/fixups/django.py", line 177, in close_database worker_1 | return self._close_database() worker_1 | File "/usr/local/lib/python3.7/site-packages/celery/fixups/django.py", line 186, in _close_database worker_1 | conn.close() worker_1 | File "/usr/local/lib/python3.7/site-packages/django/utils/asyncio.py", line 24, in inner worker_1 | return func(*args, **kwargs) worker_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 286, in close worker_1 | self.validate_thread_sharing() worker_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 558, in validate_thread_sharing worker_1 | % (self.alias, self._thread_ident, _thread.get_ident()) worker_1 | django.db.utils.DatabaseError: DatabaseWrapper objects created in a thread can only be used in that same thread. The object with alias 'default' was created in thread id 140346062341232 … -
Submitting Individual Django Formsets with AJAX
I'm trying to set up a page that will give the user the ability to edit multiple expenses at a time. Since it's not just a field or 2 that they may update i want to give them the ability to submit after updating each one. I've gotten as far as being able to serialize the form with...but not sure where to go from here. <form > <table> <div class="fieldWrapper"> {{ form.Notes.errors }} <label for="{{ form.Notes.id_for_label }}">Notes:</label> {{ form.Notes }} </div> ....rest of form.... </table> <a id="sv_btn{{forloop.counter0}}" class="btn-floating btn-large waves-effect waves-light blue" onclick="exp_sv({{forloop.counter0}})"><i class="material-icons">save</i></a> </form > and then the Java... function exp_sv(x) { console.log("Inside validate button function("+x+")") var serializeData = $('form').serialize(); console.log(serializeData); }; -
How to add a column to table throught active model in vritualenv django?
I am running an application in a virtual enviroment in Django 1.7.11. I have a model which MySQL table has 3 columns but I want to add one more column and fill it out manually. When I do that, and make changes in the model I get an 500 Internal server error. Is there a way to do it on more Pythonic way? I have installed all the necessary requirements but when I run python manage.py makemigrations I get this error: Traceback (most recent call last): File "manage.py", line 8, in from django.core.management import execute_from_command_line ImportError: No module named django.core.management All the modules are imported, and the application is running normally when I undo my changes in the model. -
DRF: how do I call a class inside another class method?
I have two separate methods: to load and validate a csv file FileUploadView(APIView) [PUT] to add new objects to the database based on their uploaded file data CsvToDatabase [POST] file upload class FileUploadView(APIView): parser_classes = (MultiPartParser, FormParser) permission_classes = (permissions.AllowAny,) def put(self, request, format=None): if 'file' not in request.data: raise ParseError("Empty content") f = request.data['file'] filename = f.name if filename.endswith('.csv'): file = default_storage.save(filename, f) r = csv_file_parser(file) status = 204 else: status = 406 r = "File format error" return Response(r, status=status) create instances class CsvToDatabase(APIView): def post(self, request, format=None): r_data = request.data ... #some logic ... serializer = VendorsCsvSerializer(data=data) try: serializer.is_valid(raise_exception=True) serializer.save() except ValidationError: return Response({"errors": (serializer.errors,)}, status=status.HTTP_400_BAD_REQUEST) else: return Response(request.data, status=status.HTTP_200_OK) urls.py urlpatterns = [ path('csv_upload/', FileUploadView.as_view(), name='csv_upload'), path('from_csv_create/', CsvToDatabase.as_view(), name='csv_vendor_create'),] At the moment I am simply passing manually to Postman the result of the PUT method of FileUploadView class (Response(r, status=status) get me json ) to POST method of CsvToDatabase class. Of course, this option is not suitable for a working application. I would like to know if there is a way to call the POST method automatically inside FileUploadView class after the .csv file is processed and json is received. I know I can transfer a … -
How to make an image responsive after setting its height and width in bootstrap
So I'm building this portfolio, and I found out ways to make the text and other stuff responsive, but I'm unable to make the picture responsive, I have set its height to 325, but when I shrink the page, the image isn't responsive. How should I make it responsive. The original image dimensions are around 1000 x 900, I tried shrinking the image size and using img-fluid but that didn't work as well. When I shrink the page When the page is in full view <img src="{% static 'shetha.jpg' %}" height="325 "/> -
Find nested JS object value from specific script tag with Beautiful Soup
I am scraping a site with beautiful soup to grab image/s, this has worked fine for every site so far and I have even managed to create some custom case-types. But one particular site is causing me issues as iit returns all the images in a JavaScript object wrapped inline in a script tag. The object is quite large as it holds all the product info, the specific bit I am looking for is nested pretty deep in productArticleDetails > [the product id] > normalImages > thumbnail > [the image path]. Like so: <script> var productArticleDetails = { ... '0399310001': { ... 'normalImages': [ { 'thumbnail': '//image-path.jpg', ... } ] } } So I am looking to just extract the image path. It is also not the only thing wrapped in a script tag in the returned 'soup', there are loads of other javascript tags in the code. So far I have saved the HTML to a variable and then run: soup = BeautifulSoup(html) scripts = soup.find_all('script') So I am left with an object that contains all the <script> elements from html Somehow within that scripts object I need to find that specific node in the correct chunk of JS … -
Django - Form returning invalid due to empty form field
In my project, I have a Django form which consists of an ImageField and a CharField. I pass this form to my template, and display it. On the form, I set the method attribute to POST. In my view I handle this request, and return a redirect in return. However form.is_valid() is returning False in my view, and I print the forms errors in the console. Here is the error returned from form.errors: <ul class="errorlist"><li>image<ul class="errorlist"><li>This field is required.</li></ul></li></ul> It is saying my ImageField input field is empty, however I definitely select a file for the ImageField in the browser, therefore I don't know the reason why it's saying that the input field is blank. My code is below. forms.py: class CreatePost(forms.Form): // The field that is not being assigned a file image = forms.ImageField(allow_empty_file=False, required=True, widget=forms.FileInput(attrs={'id': 'image'})) description = forms.CharField(max_length=100, required=False, widget=forms.TextInput(attrs={'placeholder': 'Add a caption:', 'id': 'description'})) views.py: def create(request): context = {} if request.method == "POST": form = CreatePost(request.POST) if form.is_valid(): print("YES") return redirect('home') else: print(form.errors) context['error'] = 'Please enter valid form data' else: form = CreatePost() context['form'] = form return render(request, 'create.html', context) Template: <form action="{% url 'create' %}" method="POST"> {% csrf_token %} {% for field in … -
How to set Current_company_flag using Django
I am creating a model for storing Experience... Here is my model class Experience(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=255, blank=True) company = models.CharField(max_length=255, blank=True) current_company = models.BooleanField(default=False) start_date = models.DateField(default=datetime.now) end_date = models.DateField(default=datetime.now) In this current_company is used to showing it is the current company .... This is my form for getting the data from user class ExperienceForm(forms.ModelForm): class Meta: model = Experience exclude = ['user'] This is my view class ExperienceFormView(TemplateView, LoginRequiredMixin): template_name = 'accounts/profile/expereince_form.html' form_class = ExperienceForm def post(self, request, *args, **kwargs): context = self.get_context_data() if context['form'].is_valid(): data = context['form'].save(commit=False) data.user = request.user data.save() return JsonResponse({'status': 'success', 'message': 'Created Successfully'}, status=201, safe=False) return super(ExperienceFormView, self).render_to_response(context) def get_context_data(self, **kwargs): context = super(ExperienceFormView, self).get_context_data(**kwargs) form = ExperienceForm( self.request.POST or None) # instance= None context["form"] = form return context What is the best way to implment the following use cases 1) If I enable my current_company as True then the previous object having current_company becomes False 2)If there is no previous object then ignore the first use case..... -
Django admin how do you add a queryset as a read only linked property field
This is what my admin class looks like: @admin.register(Project) class ProjectAdmin(admin.ModelAdmin): readonly_fields = ('associated_risks',) associated_risks is a queryset property that I have set in the model like so: @property def associated_risks(self): return Risk.objects.filter(control__project__associated_controls__in=self.associated_controls.all()) The isssue is that the admin page it's a read only field shown like this: Would it be possible to set it as an m2m field similar to how other m2m fields in the django admin page are set up? (multi select form) -
Error 10061 connecting to localhost:6397. No connection could be made because the target machine actively refused it
I'm trying to learn Redis with Django framework. My program is intended to count image views but when I click on the image details it gives me above mentioned error. I am unable to make connection with redis. Here's the link to my detail error http://dpaste.com/1TAJ4MF I have installed and run redis cli on WINDOWS 10 and here is a snip of my settings.py code # Configuring Redis database REDIS_HOST = 'localhost' REDIS_PORT = 6397 REDIS_DB = 0 views.py import redis from django.conf import settings def detail(request, id): profile = get_object_or_404(Profile, id=id) # increment total image views by 1 total_views = r.incr('profile:{}:views'.format(profile.id)) return render(request, 'images/detail.html', {'profile': profile, 'total_views': total_views}) detail.html <body> <img src="{{ profile.photo.url }}" width="500" height="500" alt="Image not found"> <br> {{ profile.user.username.title }}. {{ profile.dob }} <br> {{ total_views }} view{{ total_views|pluralize }} </body> -
My Django web app isn't functioning properly
I'm fairly new at Django and I've been making a login and registration form using bootstrap and then connecting the bootstrap template with Django. The form has a sign in and sign-up page which has a smooth transition when you click on each of them. But when I click on the sign-up, nothings happening.I've set up the static files and the website is displaying correctly although not functioning correctly. Can someone help me resolve this problem? I've provided the CSS file here https://easyupload.io/gq48hs. The login and registration page looks like this https://ibb.co/jr4pm3N Bootstrap {% load static %} <!DOCTYPE html> <html lang="en" > <head> <meta charset="UTF-8"> <title>Online Timetable - Student Login and registration form</title> <link rel='stylesheet' href='https://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css'><link rel="stylesheet" href="{%static 'css/style.css' %}"/> </head> <body> <!-- partial:index.partial.html --> Login & registration Form --> SIGN IN SIGN UP USERNAME PASSWORD Keep me signed in Forgot password? USERNAME E-MAIL PASSWORD CONFIRM PASSWORD I agree </body> <!-- partial --> <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script> <script src='https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js'></script> <script src="{% static 'css/script.js' %}"></script> </body> </html> $('.btn-enregistrer').click(function() { $('.connexion').addClass('remove-section'); $('.enregistrer').removeClass('active-section'); $('.btn-enregistrer').removeClass('active'); $('.btn-connexion').addClass('active'); }); $('.btn-connexion').click(function() { $('.connexion').removeClass('remove-section'); $('.enregistrer').addClass('active-section'); $('.btn-enregistrer').addClass('active'); $('.btn-connexion').removeClass('active'); }); URLS.Py from django.urls import path from .import views urlpatterns = [ path('',views.login), ] Views.py from django.shortcuts import render from django.http import HttpResponse … -
Validar campo antes de salvar model django
Estou criando uma aplicação que recebe o cpf do usuário. Quero validar o CPF antes de salvar. Já tenho a função que faz a validação, mas como chamo antes de salvar? cpf = models.IntegerField(max_length=11, null=False, unique=True) O serializer: class SellerSerializer(serializers.ModelSerializer): class Meta: model = Seller fields = '__all__' O viewset: class SellerViewSet(ModelViewSet): queryset = Seller.objects.all() serializer_class = SellerSerializer -
Heroku Deployment - ModuleNotFoundError: No module named 'eventshow.local_settings' Error while running '$ python manage.py collectstatic --noinput'
I am running into the following issue when trying to deploy my Django-Postgres app on Heroku: >❯git push heroku master Enumerating objects: 246, done. Counting objects: 100% (246/246), done. Delta compression using up to 4 threads Compressing objects: 100% (108/108), done. Writing objects: 100% (246/246), 4.87 MiB | 1.62 MiB/s, done. Total 246 (delta 114), reused 239 (delta 112) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing python-3.6.10 remote: -----> Installing pip remote: -----> Installing SQLite3 remote: Sqlite3 successfully installed. remote: -----> Installing requirements with pip remote: Collecting asgiref==3.2.3 remote: Downloading asgiref-3.2.3-py2.py3-none-any.whl (18 kB) remote: Collecting astroid==2.3.3 remote: Downloading astroid-2.3.3-py3-none-any.whl (205 kB) remote: Collecting autopep8==1.5 remote: Downloading autopep8-1.5.tar.gz (116 kB) remote: Collecting dj-database-url==0.5.0 remote: Downloading dj_database_url-0.5.0-py2.py3-none-any.whl (5.5 kB) remote: Collecting Django==3.0.4 remote: Downloading Django-3.0.4-py3-none-any.whl (7.5 MB) remote: Collecting django-extensions==2.2.8 remote: Downloading django_extensions-2.2.8-py2.py3-none-any.whl (224 kB) remote: Collecting django-heroku==0.3.1 remote: Downloading django_heroku-0.3.1-py2.py3-none-any.whl (6.2 kB) remote: Collecting djangorestframework==3.11.0 remote: Downloading djangorestframework-3.11.0-py3-none-any.whl (911 kB) remote: Collecting Faker==4.0.1 remote: Downloading Faker-4.0.1-py3-none-any.whl (994 kB) remote: Collecting gunicorn==20.0.4 remote: Downloading gunicorn-20.0.4-py2.py3-none-any.whl (77 kB) remote: Collecting isort==4.3.21 remote: Downloading isort-4.3.21-py2.py3-none-any.whl (42 kB) remote: Collecting lazy-object-proxy==1.4.3 remote: Downloading lazy_object_proxy-1.4.3-cp36-cp36m-manylinux1_x86_64.whl (55 kB) remote: Collecting mccabe==0.6.1 remote: Downloading mccabe-0.6.1-py2.py3-none-any.whl (8.6 kB) remote: … -
how to get individual user API by using django rest framework knox
Before I implement token authentication, it worked fine to grab each user, GET: http://localhost:8000/users/2/ { "url": "http://localhost:8000/users/2/", "id": 2, "username": "foo", "boards": [ "http://localhost:8000/boards/15/" ] }, After I implement knox token authentication, #settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ('knox.auth.TokenAuthentication',), } #users/views.py class UserDetail(generics.RetrieveAPIView): permission_classes = [permissions.IsAuthenticated] queryset = User.objects.all() serializer_class = UserSerializer def get_object(self): return self.request.use #users/urls.py app_name = 'users' urlpatterns = [ path('', UserList.as_view(), name='user-list'), path('<int:pk>/', UserDetail.as_view(), name='user-detail'), path('register/', RegistrationAPI.as_view(), name='user-register'), path('login/', LoginAPI.as_view(), name='user-login'), path('logout/', knox_views.LogoutView.as_view(), name='user-logout'), # path('', api_root) ] urlpatterns = format_suffix_patterns(urlpatterns) # users/serializer.py class UserSerializer(serializers.HyperlinkedModelSerializer): boards = serializers.HyperlinkedRelatedField( view_name='board:board-detail', lookup_field='pk', many=True, queryset=Board.objects.all() ) url = serializers.HyperlinkedIdentityField( read_only=True, lookup_field='pk', view_name="users:user-detail") class Meta: model = User fields = ('url', 'id', 'username', 'boards') class CreateSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField( read_only=True, lookup_field='pk', view_name="users:user-detail") def create(self, validated_data): user = User.objects.create_user( validated_data['username'], None, validated_data['password'] ) return user class Meta: model = User fields = ('url', 'id', 'username', 'password') class LoginUserSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, data): user = authenticate(**data) if user and user.is_active: return user raise serializers.ValidationError("unable to log in with provided credential") Now I am getting 401 error, GET: http://localhost:8000/users/2/ { "detail": "Authentication credentials were not provided." } Even, POST:http://localhost:8000/logout/ has the same 401 Unauthorized error. I tried login first … -
django polymorphic dumpdata command fails - django.db.utils.IntegrityError: Problem installing fixtures
I'm using package django-polymorphic==2.1.2 Django==2.2 When trying to dumpdata for testing it fails with this message: Error Traceback (most recent call last): File "/home/federico/Repositories/APC/venv/lib/python3.6/site-packages/django/test/testcases.py", line 1131, in setUpClass call_command('loaddata', *cls.fixtures, **{'verbosity': 0, 'database': db_name}) File "/home/federico/Repositories/APC/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 148, in call_command return command.execute(*args, **defaults) File "/home/federico/Repositories/APC/venv/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/federico/Repositories/APC/venv/lib/python3.6/site-packages/django/core/management/commands/loaddata.py", line 72, in handle self.loaddata(fixture_labels) File "/home/federico/Repositories/APC/venv/lib/python3.6/site-packages/django/core/management/commands/loaddata.py", line 122, in loaddata connection.check_constraints(table_names=table_names) File "/home/federico/Repositories/APC/venv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 318, in check_constraints bad_value, referenced_table_name, referenced_column_name django.db.utils.IntegrityError: Problem installing fixtures: The row in table 'core_faultagv' with primary key '1' has an invalid foreign key: core_faultagv.fault_ptr_id contains a value '1' that does not have a corresponding value in core_fault.id. I tried using "--natural-foreign" and "--natural-primary" as arguments for manage.py dumpdata but it still fails. These are my models: class Fault(PolymorphicModel): active = models.BooleanField(default=False) equipment = models.CharField(choices=EquipmentChoices.choices(), max_length=10) fault_text = models.CharField(max_length=255) start_time = models.DateTimeField(auto_now=True) def get_vehicle_id(self): return None class FaultAGV(Fault): error_code = models.IntegerField() vehicle_id = models.IntegerField() def get_vehicle_id(self): return self.vehicle_id class FaultPLC(Fault): bit = models.IntegerField() index = models.IntegerField() Any suggestion? -
import error in python in django framework
from django.contrib import admin from django.urls import url from . import views urlpatterns = [ # path('admin/', admin.site.urls), url(r'^admin/',admin.site.urls), url(r'^about/$',views.about), url(r'^$',views.homepage), ] this is python code in django framework . i have successfully installed django but i dont know why this is showing an error . actually i was just started with django so have a look in the fault . may be this is because of that it cant reach to urls and contrib directory . please help Thanks in advance . C:\Users\My Loptop\Desktop\django\djangonautic> C:\Users\My Loptop\Desktop\django\djangonautic>python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\My Loptop\AppData\Local\Programs\Python\Python36-32\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Users\My Loptop\AppData\Local\Programs\Python\Python36-32\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "C:\Users\My Loptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\My Loptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\My Loptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 395, in check include_deployment_checks=include_deployment_checks, File "C:\Users\My Loptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\My Loptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\My Loptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\My Loptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\My Loptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\resolvers.py", line 407, in check for pattern in self.url_patterns: File "C:\Users\My Loptop\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\functional.py", … -
Filter inline objects based on model foreign key object variable
I am building a relatively simple pizza shop. There is a Pizza model with category choices field. There's also an OrderItem model that refers to Pizza: class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, verbose_name=_('OrderItem|Order', 'Order')) pizza = models.ForeignKey(Pizza, on_delete=models.CASCADE, verbose_name=_('OrderItem|Item', 'Item')) quantity = models.PositiveSmallIntegerField(validators=[MinValueValidator(1)], verbose_name=_('OrderItem|Quantity', 'Quantity')) @property def price(self): return self.pizza.price * self.quantity def __str__(self): return f"{self.pizza.id}" In admin.py there's an inline that uses this model when showing an order: class OrderItemInline(admin.TabularInline): model = OrderItem fields = ('pizza', 'quantity', 'price_admin',) readonly_fields = ('price_admin',) extra = 0 How do I make it filter order items based on pizza category? For example to only be able to select pizzas from one specific category. -
django appending class object on refresh
I have made some class on django views.py. I am having issues with them. The previously loaded data is getting appended on refresh. Instead of deleting the previous objects of the class object it is appending it with new objects. class topic_sub_topic: def __init__(self,request,topic): self.topic = topic sub_topics = topics_to_subtopics.objects.filter(topic = topic) x = [] for sub_topic in sub_topics: x += [sub_topic.subtopic] self.sub_topics = x class course_detail: content = [] def __init__(self,request,course): course = courses.objects.get(slug = course) self.course = course topics = course_to_topics.objects.filter(course = course) if not topics: return for topic in topics: self.content += [topic_sub_topic(request,topic.topic)] def view_course_deatail(request,course): obj = course_detail(request,course) return render(request,'create/coursedetail.html',{'obj':obj}) Whenever I refresh the template django simply appends the older generated class object with new one. -
Contact Form with Django 3, G Suite - email sending error
Goal Deploying a landing page on Digital Ocean built with Django 3. Adding my G suite account to the contact form so people can type in their email, subject, message and send it to me. What I have done I have built my contact from with the following guide. I have tested it and it prints out all the parameters in the terminal as it should Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: helllo From: customeremail@gmail.com To: admin@example.com Date: Tue, 17 Mar 2020 14:29:40 -0000 Message-ID: <12121212121212.1222212121212.1212121212121212@mymachinename.local> This is the message. I have purchased a G Suite subscription that contains G Suite SMTP relay service that can send 10'000 email/day. ERROR I have run it and received the following e-mail: Critical security alert Google <no-reply@accounts.google.com> to me Sign-in attempt was blocked myname@businessemaildomainname.com Someone just used your password to try to sign in to your account from a non-Google app. Google blocked them, but you should check what happened. Review your account activity to make sure no one else has access. Check activity I have looked up a couple of posts but none of them answered my question like G Suite and Django for SMTP Why can not get email … -
Unable to POST data to django function using ajax
I am trying to add data and view data to/from django database through AJAX calls, fetching data works fine but adding data doesnt work. I getting following error: Method Not Allowed (POST): /mymodels/ Method Not Allowed: /mymodels/ [17/Mar/2020 22:27:24] "POST /mymodels/ HTTP/1.1" 405 0 and in browser console: 0: undefined My ajax function: $(document).on('submit', '#myform', function(e){ $.ajax({ type: 'POST', url: `/mymodels/create`, data:{ first_name:$('#first_name').val(), last_name:$('#last_name').val(), age:$('#age').val() }, success:function(json){ console.log("Data submitted"); }, error:function(xhr,errmsg,err) { console.log(xhr.status + ": " + xhr.responseText); } }) }) urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('mymodels/', TemplateView.as_view(template_name='crud_app/main.html'),name='mymodel_main'), path('mymodels/list', views.MyModelList.as_view(), name='mymodel_list'), path('mymodels/create', views.MyModelCreate.as_view(), name='mymodel_create'), path('mymodels/update/<int:pk>', views.MyModelUpdate.as_view(), name='mymodel_update'), path('mymodels/delete/<int:pk>', views.MyModelDelete.as_view(), name='mymodel_delete'), path('mymodels/<int:pk>', views.MyModelDetail.as_view(), name='mymodel_detail'), ] view: class MyModelCreate(CreateView): def post(self,request): data = dict() form = MyModelForm(request.POST) if form.is_valid(): my_model = form.save() data['my_model'] = model_to_dict(my_model) else: data['error'] = 'Form invlaid' return JsonResponse(data) and finally my html form: <form class="form-group" id="myform" method="POST"> {% csrf_token %} <label for="first_name">First Name</label> <input type="text" class="form-control" name="" id="first_name" placeholder=""> <label for="last_name">Last Name</label> <input type="text" class="form-control" name="" id="age_name" placeholder=""> <label for="age">age</label> <input type="text" class="form-control" name="" id="age" placeholder=""> <input type="submit" class="btnSubmit btn btn-primary" value="Submit"> </form> {% endblock %} {% block extrajs %} <script src="{% static 'js/app.js' %}"></script> {% endblock %} -
docker-compose django app cannot find postgresql db
I'm trying to create a Django app in a docker container. The app would use a postgres db with postgis extension, which I have in another database. I'm trying to solve this using docker-compose but can not get it working. I can get the app working without the container with the database containerized just fine. I can also get the app working in a container using a sqlite db (so a file included without external container dependencies). Whatever I do, it can't find the database. My docker-compose file: version: '3.7' services: postgis: image: kartoza/postgis:12.1 volumes: - postgres_data:/var/lib/postgresql/data/ ports: - "${POSTGRES_PORT}:5432" environment: - POSTGRES_USER=${POSTGRES_USER} - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} - POSTGRES_DB=${POSTGRES_DB} env_file: - .env web: build: . # command: sh -c "/wait && python manage.py migrate --no-input && python /code/app/manage.py runserver 0.0.0.0:${APP_PORT}" command: sh -c "python manage.py migrate --no-input && python /code/app/manage.py runserver 0.0.0.0:${APP_PORT}" # restart: on-failure ports: - "${APP_PORT}:8000" volumes: - .:/code depends_on: - postgis env_file: - .env environment: WAIT_HOSTS: 0.0.0.0:${POSTGRES_PORT} volumes: postgres_data: name: ${POSTGRES_VOLUME} My Dockerfile (of the app): # Pull base image FROM python:3.7 LABEL maintainer="yb.leeuwen@portofrotterdam.com" # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies # RUN pip install pipenv RUN pip install pipenv RUN mkdir /code/ …