Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Hosting single project in different server
I've a django web application and it contains lots of app like (event, result, exam, ....). Suppose in the future it become heavy application. Now my question is can split event app from project and host it somewhere else. like in different server and link back it to project. Here I need suggestion, if it is possible then how if not then is there any alternative way. -
Encoding error when migrating django app from python 2 to python 3
Im migrating a django application from python 2.7.15 to python 3.6.10. I have code like as follows: re.compile(ur'({number}\d+)'.format(number=numeral_constant.NUMBER_REPLACE_TEXT), re.UNICODE) This works in Python 2 but to make it work in Python 3, i have to use r instead of ur as strings are unicode by default in Python 3 and do re.compile(r'({number}\d+)'.format(number=numeral_constant.NUMBER_REPLACE_TEXT), re.UNICODE) This now works in Python 3 but breaks in Python 2 and i get the error 'ascii' codec can't encode characters in position 3-4: ordinal not in range(128). Is there any way i modify the code such that it works in both Python 2 and Python 3 ? Thanks -
Django admin pagination for inlines
I know the question been asked before but i'm having problem implemented it Currently i'm trying to do inlines for models since inline can take up alot of loading without pagination After many time looking up on how to do it, it all leads to this comment about the way to implemented it. I currently have problem as i don't use django-suit so some template tag in that answer can't be use: {% load i18n suit_list %} {% include 'admin/edit_inline/tabular.html' %} {% block after_inline %} <div class="suit-tab suit-tab-relations"> {% with inline_admin_formset.formset.cl as cl %} {% if cl.paginator %} {% pagination cl %} {% endif %} {% endwith %} </div> <!-- Following javaScript is required if you have tabs, otherwise you can remove this JS code --> <script type="text/javascript"> (function ($) { Suit.$('.pagination li a').on('click', function () { if (document.location.hash) { $(this).attr('href', $(this).attr('href') + '#' + document.location.hash.substr(1)); } }); }(Suit.$)); </script> {% endblock %} I tried to narrow the template code down to what i really need: {% include 'admin/edit_inline/tabular.html' %} {% block after_inline %} <div> {% with inline_admin_formset.formset.cl as cl %} {% if cl.paginator %} {% pagination cl %} {% endif %} {% endwith %} </div> {% endblock %} But … -
Hi, How can i sum all elements in sqlite database together to get the sum total of the number using Flask(python)
The model class returnsdb2 (db.Model,UserMixin): id = db.Column(db.Integer,primary_key=True) totaltithes = db.Column(db.BigInteger,default=0) today=db.Column(db.DateTime, nullable=False, default=datetime.utcnow) @app.route('/service' , methods=['GET', 'POST']) def service(): alltithes = returnsdb2.query.all() for alltithe in alltithes: print (sum(alltithe.totaltithes)) I'm trying to add all the list together to get the sum total output. -
How can I test function with request.is_ajax() and request.method=='POST' in Django using unittest?
I have next function def edit_resolution_text_view(self, request): if request.method == 'POST' and request.is_ajax(): resolution = request.POST.get('resolution') donation_id = request.POST.get('donation') result = Donation.objects.filter(pk=donation_id).\ update(resolution_note=resolution) if not result: return JsonResponse({'message': 'Error'}) return JsonResponse({'resolution': resolution}) return JsonResponse({'message': 'Error'}) How can to test it using unittest -
django.core.exceptions.FieldError: Cannot resolve keyword error while unit testing DRF APIView
Getting django.core.exceptions.FieldError: Cannot resolve keyword 'bank_account' into field while testing DRF APIView that is supposed to create a new record in model. Serializer of the model has a custom field called bank_account that maps to model field to_account. models class Transaction(models.Model): """Abstract class for common transaction fields""" id = models.BigAutoField(primary_key=True, editable=False) # using uuid data for making reference for every transaction object txn_id = models.CharField(max_length=50, unique=True, editable=False) to_account = models.CharField(max_length=20, editable=False) amount = models.DecimalField(max_digits=10, decimal_places=4, editable=False) class Meta: abstract = True class CashBabaToConnectTransactionModel(Transaction): class Meta: db_table = "cash_baba_to_connect_transaction" serializers class CashBabaToConnectTransactionModelSerializer(serializers.ModelSerializer): bank_account = serializers.CharField(source='to_account') # Custom field that maps to model field to_account class Meta: model = CashBabaToConnectTransactionModel fields = ('txn_id', 'amount', 'bank_account') test from django.test import TestCase class TestNewTransactionView(TestCase): def setUp(self) -> None: self.NEW_TRANSACTION_URL = reverse('cash_baba_new_transaction') self.request_data = {"txn_id": "123", "amount": "100", "bank_account": "xxxxx" } def test_new_record_is_created(self): record_count_before = CashBabaToConnectTransactionModel.objects.filter( **self.request_data).count() response = self.client.post(self.NEW_TRANSACTION_URL, data=self.request_data, format='json') record_count_after = CashBabaToConnectTransactionModel.objects.filter( **self.request_data).count() self.assertEqual(record_count_after, record_count_before + 1) view class NewTransactionView(APIView): model_name = CashBabaToConnectTransactionModel serializer = CashBabaToConnectTransactionModelSerializer() def post(self, request): """API used to send money to connect account""" serializer = CashBabaToConnectTransactionModelSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response("", status=status.HTTP_201_CREATED) -
Django: Editing a form on third party packages?
I'm trying to use https://django-organizations.readthedocs.io/en/latest/ in my project and the models are automatically migrated with a "slug" field - something I wish to not have, everything else is more or less fine with the package, my question is, how would I remove that SlugField and keep everything in the package as is? -
How to provide a parameter to a router in django rest API?
So the url I am trying to achieve looks like this: api/tech/?belongs=id My router looks like this: router = routers.DefaultRouter() router.register('tech', TechViewSet, basename="tech") urlpatterns = [ path('', include(router.urls)), re_path(r'^tech/(?P<belongs>)$', include(router.urls), name="info"), My viewset looks like this (Also has a retrieve and list functions): @action(detail=True, url_path='^tech/(?P<belongs>)$', methods=['get']) def retrieve1(self, request, group=None): pass How to get this url working.. api/tech/?belongs=id Please help. and Im sorry, I'm still learning and the routing part is confusing.. Thankyou so much -
filter all the installed apps with their model and permission in django
I want to display list of all the installed app and model as well as their permission. for example app_name_1 model_name_1 permission_1 permission_2 ........... model_name_2 permission_1 permission_2 ........... app_name_2 model_name_1 permission_1 permission_2 ........... model_name_2 permission_1 permission_2 ........... and so on. -
Graphql trying to create an object of get_user_model : __init__() got an unexpected keyword argument 'request'
I've recently started learning GraphQL. I created a Mutation for a custom-defined model and it's working fine. But when I try to do the same for the Django built-in user model. I'm getting an error. Not able to resolve it. I'm trying to create a new user by creating an object of get_user_model through GraphQL. class CreateUser(graphene.Mutation): user = graphene.Field(UserType) class Arguments: username = graphene.String(required=True) password = graphene.String(required=True) email = graphene.String(request=True) def mutate(self,info,username,password,email): user = get_user_model(username=username,email=email) user.set_password(password) user.save() return CreateUser(user=user) class Mutation(graphene.ObjectType): create_user = CreateUser.Field() Getting the above error. Not sure what's the problem. Please anyone explain. Traceback error: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/graphql/ Django Version: 3.0.3 Python Version: 3.6.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'graphene_django', 'links'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/Users/sunilhn/Documents/programming/Envs/graphenv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/sunilhn/Documents/programming/Envs/graphenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/sunilhn/Documents/programming/Envs/graphenv/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/sunilhn/Documents/programming/Envs/graphenv/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Users/sunilhn/Documents/programming/Envs/graphenv/lib/python3.6/site-packages/django/views/generic/base.py", line 62, in view self = cls(**initkwargs) File "/Users/sunilhn/Documents/programming/Envs/graphenv/lib/python3.6/site-packages/graphene_django/views.py", line 79, in __init__ schema = graphene_settings.SCHEMA File "/Users/sunilhn/Documents/programming/Envs/graphenv/lib/python3.6/site-packages/graphene_django/settings.py", line 117, in __getattr__ val … -
Django 3 UUID router returns 404
I have a simple model: from django.db import models import uuid class Localhost (models.Model): name = models.CharField(max_length=255) date = models.DateTimeField() id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) def __str__(self): return self.name views def localhost(request, localhost_id): localhost = get_object_or_404(Localhost, id=loalhost_id) return render(request, 'local.html', {'localhost':localhost}) and urls.py urlpatterns = [ path('', views.home, name='home'), path( 'f/<uuid:localhost_id>/', views.localhost, name='localhost'), ] I have a record in the DB as tested here SELECT * FROM `app_localhost` WHERE `id` = '5d7d555861f2487d8ea147e8b274e267' but loading the route with /f/5d7d555861f2487d8ea147e8b274e267 returns not found Not Found: /f/5d7d555861f2487d8ea147e8b274e267 [10/Feb/2020 10:06:10] "GET /f/5d7d555861f2487d8ea147e8b274e267 HTTP/1.1" 404 2682 There is probably something I am doing wrong but I can't figure out what. I did check the manual and everything seems to be according to the specifications. -
'Manager' object has no attribute '__getitem__'
i'm using Django rest Framework to build an app , iwant to change the language of the app when the user want to change it ,so i made two serializers for each dynamic titles i have in the app one for english and the other for arabic ,i want to give another params called lang to change the response of the api view to use another serializer ==> models.py class RewardSubCategory(models.Model): category = models.ForeignKey( 'RewardCategory', on_delete=models.DO_NOTHING) title = models.CharField(max_length=200) ar_title = models.CharField(max_length=200, null=True, blank=True) picture = models.ImageField(upload_to=file_upload) def __unicode__(self): return str(self.title) class RewardCategory(models.Model): title = models.CharField(max_length=200) ar_title = models.CharField(max_length=200, null=True, blank=True) picture = models.ImageField(upload_to=file_upload) def __unicode__(self): return str(self.title) ==> serializers.py class RewardSubCategorySerializer(serializers.ModelSerializer): window = serializers.SerializerMethodField() affilates = serializers.SerializerMethodField() class Meta: model = models.RewardSubCategory fields = ('id', 'category', 'title', 'picture', 'window', 'affilates') depth = 1 def get_window(self, obj): windows = models.SubCategoryWindow.objects.filter( sub_category=int(obj.id)) data = SubCategoryWindowSerializer(windows, many=True).data return data def get_affilates(self, obj): affilates = models.affilate.objects.filter(sub_category=int(obj.id)) data = AffilateSerializer(affilates, many=True).data return data class ArabicRewardSubCategorySerializer(serializers.ModelSerializer): window = serializers.SerializerMethodField() affilates = serializers.SerializerMethodField() class Meta: model = models.RewardSubCategory exclude = ('title') depth = 1 def get_window(self, obj): windows = models.SubCategoryWindow.objects.filter( sub_category=int(obj.id)) data = SubCategoryWindowSerializer(windows, many=True).data return data def get_affilates(self, obj): affilates = models.affilate.objects.filter(sub_category=int(obj.id)) data = AffilateSerializer(affilates, … -
Lazy evaluation in generator with Django model objects
I'm trying to understand how to use a Django QuerySet in a Python generator so that it evaluates lazily. The documentation does not mention generators explicitly, this seems to be the only (more or less) related remark, but it does not clarify my question: You can evaluate a QuerySet in the following ways: Iteration. A QuerySet is iterable, and it executes its database query the first time you iterate over it. [...] I have a Django model like this: class Document(models.Model): text = [...] @cached_property def process(self): [...] Now I try this: processed = (doc.process for doc in Document.objects.all()) I noticed, however, that this triggers the process() method immediately for all of the objects, which results in exploding memory consumption. Investigating step by step: docs = Document.objects.all() test = (doc for doc in docs) Document.objects.all() does not trigger any evaluation, it only creates the QuerySet, as expected. However, the second line (test) already loads the whole document set into memory, so the process() call as shown above is apparently not an issue. It looks to me like creating a generator comprehension from a QuerySet already triggers the Django database call. If that is the case, how can I properly achieve … -
Django Microservices Admin Authentication
I am building an application using Django Web Framework and Django Rest Framework (Microservices architecture). It has 3 services: Authentication Sa Sb The Authentication service needs django inbuilt authentication Middleware. But those are not required in Sa and Sb. How can i get rid of those in other services ? and also How will the admin view of other services will work ?, I meant the Login for viewing the default admin site in django. Currently the expected flow is If any request comes to Sa then first a call will be made to Authentication service to verify the jwt token and then it will be processed. -
Difference between @app.task and @shared.task when using celery with django
I have an API which takes a POST request, with user credentials and runs some tasks fetching data from AWS in the background. It is working fine with celery. Now, the task is to create it into a periodic task, i.e. the function that fetches all the data from AWS should be called upon each hour. # Views.py initiate_discovery_tasks([resource_group.id]) schedule, created = IntervalSchedule.objects.get_or_create( every=60, period=IntervalSchedule.MINUTES, ) #### Making a Periodic task for initiate discovery. PeriodicTask.objects.create( interval=schedule, name=f'{resource_group.id} ----> {resource_group.project.name}' f' || Initiate Discovery Task', task='resources.tasks.initiate_discovery_tasks', args=json.dumps([[resource_group.id]]), # expires=datetime.utcnow() + timedelta(seconds=30) ) This is my View, it's supposed to run all the tasks once then create a periodic task to run the same task after every 60 minutes. # tasks.py def initiate_discovery_tasks(resource_groups_ids=None): if not isinstance(resource_groups_ids, list): # if passed resource_groups in param it should be a list raise Exception("resource_groups_ids param must be a list ") discovery_ec2_task.apply_async(kwargs={"resource_groups_ids": resource_groups_ids}) discovery_alb_task.apply_async(kwargs={"resource_groups_ids": resource_groups_ids}) discovery_rds_task.apply_async(kwargs={"resource_groups_ids": resource_groups_ids}) @shared_task def discovery_ec2_task(resource_groups_ids=None): resource_groups = get_resource_groups(resource_groups_ids) for resource_group in resource_groups: obj = EC2Client( resource_group.get_resource_group_json(), access_key_id=resource_group.access_key, access_secret_key=resource_group.secret_key, default_region=resource_group.default_region ) obj.input_steam() @shared_task def discovery_rds_task(resource_groups_ids=None): resource_groups = get_resource_groups(resource_groups_ids) for resource_group in resource_groups: obj = RDSClient( resource_group.get_resource_group_json(), access_key_id=resource_group.access_key, access_secret_key=resource_group.secret_key, default_region=resource_group.default_region ) obj.input_steam() @shared_task def discovery_alb_task(resource_groups_ids=None): resource_groups = get_resource_groups(resource_groups_ids) for resource_group in resource_groups: obj = … -
How to create a subform for a ManyToMany with intermediate table using Django's Forms?
The code here looks really good and helpful, but what if I want a ManyToMany with the use of intermediate table? I have a Person, and Phone, and a person can have many phones, and a phone can be linked to many persons. Thus I have a PersonPhone intermediate table. class PersonPhone(BaseModel): person = models.ForeignKey(Person, on_delete=models.CASCADE, blank=False, null=False) phone_type = models.ForeignKey(PhoneType, models.CASCADE, blank=False, null=False) phone = models.ForeignKey(Phone, on_delete=models.CASCADE, blank=False, null=False) I've done a code inspired from the answer above, with PersonPhone. But the form asks me to select an already existing phone. I'd like to add the possibility to create dynamically a new Phone. PersonPhoneForm class PersonPhoneForm(forms.ModelForm): class Meta: model = PersonPhone fields = ('phone_type', 'phone') PersonPhoneFormSet = inlineformset_factory(Person, PersonPhone, form=PersonPhoneForm, extra=1) PersonPhonesCreate view class PersonPhonesCreate(generic.CreateView): template_name = 'person_phones.html' model = Person fields = '__all__' success_url = reverse_lazy('profile-list') def __init__(self, **kwargs): self.object = None super().__init__(**kwargs) def get_context_data(self, **kwargs): result = super().get_context_data(**kwargs) if self.request.POST: result['person_phones'] = PersonPhoneFormSet(self.request.POST) else: result['person_phones'] = PersonPhoneFormSet() return result def form_valid(self, form): context = self.get_context_data() person_phones = context['person_phones'] with transaction.atomic(): self.object = form.save() if person_phones.is_valid(): person_phones.instance = self.object person_phones.save() return super().form_valid(form) How would you do? -
django + ajax post form
i tru use ajax with django. There are 2 forms. the first with the name and mail. and a quick form with a confirmation code that comes in the mail. views.py def get_name(request): if request.method == 'POST': user_code = generate_code(8) subject = 'code' message = user_code form = NameForm(request.POST) if form.is_valid(): Registration.objects.create(fio=request.POST['fio'],mail=request.POST['mail']) send_mail(subject, message,settings.EMAIL_HOST_USER,[mail],fail_silently=False) return JsonResponse({ 'form1': render_to_string( 'registers/endreg.html', {'form': NameForm1()},request=request ) }) else: form = NameForm() return render(request, 'registers/detail.html', {'form': form}) template (detail.html) <form action="" method="post" autocomplete="off" id="my_form"> {% csrf_token %} <div class="contact-form" > <h1>{%trans 'Registers' %}</h1> <div class="txtb">{{form.fio.label}} {{form.fio}}{{form.fio.help_text}}</div> <div class="txtb">{{form.phone.label}} {{form.phone}}{{form.phone.help_text}}</div> <input type="submit" value="{%trans 'send' %}" class="btn" id="btn"> </div> </form> I am hanging an event to submit this form $(document).ready(function() { $("#my_form").submit(function(event) { event.preventDefault(); $this = $(this); $.ajax({ type: "POST", data: $this.serialize(), success: function(data) { console.log(data); var parent=$("#my_form").parent(); parent.html(data.form1); }, error: function(data) { console.log(data); $this.html(data); } }); }); }); ajax request works and get my 2 form (endreg.html) <form action="endreg/" method="post" autocomplete="off" id="my_form2"> {% csrf_token %} <div class="verification" > <div class="ver"> {{form}} </div> <input type="submit" value="{%trans 'send' %}" class="btn1" > </div> </form> views.py def endreg(request): if request.method == 'POST': form = NameForm1(request.POST) if form.is_valid(): code_use = form.cleaned_data.get("key") try: user = Registration.objects.get(code=code_use) user.verification = True user.save() messages.warning(request, u'thanks.') … -
NoReverseMatch at /login/ Reverse for 'teacher_dashboard' with arguments '({'teacher':object (2)>},)' not found. 1 pattern(s) tried:
Views.py def Login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request , username=username , password=password) if user is not None: try: is_teacher= Teacher.objects.get(profile_id=user.id) except Teacher.DoesNotExist: is_teacher = None if is_teacher is not None: login(request , user) is_teacher= Teacher.objects.get(profile_id=user.id) return redirect('teacher_dashboard' , {'teacher' : is_teacher}) else: login(request , user) return redirect('student_dashboard' ) return render (request , "pages/login.html") urls.py path('teacher_dashboard/', views.TeacherDashboard , name='teacher_dashboard'), path('student_dashboard/', views.StudentDashboard , name='student_dashboard'), i want to send queryset with a html page when its redireted -
Django JsonResponse unexpectected behaviour
I am creating a photo gallery using Django-photologue and Jquery similar to FB. I let users to select a photo to create Gallery and later add photos. I use JQuery-FileUpload-Plugin. When I post the image I get the JsonResponse. But instead of opening the modal I get of my data shown in browser. I have created my template: <form method="post" id="album-preview-form" enctype="multipart/form-data"> {% csrf_token %} <input id="fileuploader" type="file" name="image" multiple style="display: none;" data-url="{% url 'profiles:photos' %}" data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}"}'> <a href="#" class="btn btn-primary btn-md-2 gallery-start">{% trans 'Create Album' %} +</a> </form> //error is in this script my best shot: $(".gallery-start").click(function(e) { e.preventDefault(); $("#fileuploader").click(); $("#fileuploader").onchange = function() { var serializedData = $(this).serialize(); console.log(serializedData); $("#album-preview-form").submit(function(){ var serializedData = $(this).serialize(); console.log(serializedData); $.ajax({ type:'POST', url: "{% url 'profiles:photos' %}", data: serializedData, success: function(response){ //modal does not show $("#album-create-form").modal('show'); }, error: function(response) { alert(response["responseJSON"]["error"]); } }); }); }; }); In my view I have added get and post: class BasicUploadView(View): def get(self, request, *args, **kwargs): galleries = Gallery.objects.all() context = { 'galleries':galleries } return render(self.request, 'classroom/accounts/photos-upload.html', context ) def post(self, request, *args, **kwargs): #gallery=Gallery.objects.create(title=generate_random_string(), slug=generate_random_string(), user_id=self.request.user.id) photo_form = PhotoModelForm( data=request.POST, files=request.FILES) user=self.request.user if photo_form.is_valid(): photo_form.instance.user_id = self.request.user.id photo_form.instance.user = user photo_form.instance.title = (photo_form.instance.image.name)[5] + … -
getting this error while running django project
Traceback (most recent call last): File "/home/omprakashg/.local/lib/python3.6/site-packages/django/core/management/init.py", line 357, in execute autoreload.check_errors(django.setup)() File "/home/omprakashg/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/omprakashg/.local/lib/python3.6/site-packages/django/init.py", line 16, in setup from django.urls import set_script_prefix File "/home/omprakashg/.local/lib/python3.6/site-packages/django/urls/init.py", line 1, in from .base import ( File "/home/omprakashg/.local/lib/python3.6/site-packages/django/urls/base.py", line 9, in from .exceptions import NoReverseMatch, Resolver404 File "/home/omprakashg/.local/lib/python3.6/site-packages/django/urls/exceptions.py", line 1, in from django.http import Http404 File "/home/omprakashg/.local/lib/python3.6/site-packages/django/http/init.py", line 5, in from django.http.response import ( File "/home/omprakashg/.local/lib/python3.6/site-packages/django/http/response.py", line 15, in from django.core.serializers.json import DjangoJSONEncoder File "/home/omprakashg/.local/lib/python3.6/site-packages/django/core/serializers/init.py", line 23, in from django.core.serializers.base import SerializerDoesNotExist File "/home/omprakashg/.local/lib/python3.6/site-packages/django/core/serializers/base.py", line 7, in from django.db import models File "/home/omprakashg/.local/lib/python3.6/site-packages/django/db/models/init.py", line 3, in from django.db.models.aggregates import * # NOQA File "/home/omprakashg/.local/lib/python3.6/site-packages/django/db/models/aggregates.py", line 5, in from django.db.models.expressions import Case, Func, Star, When File "/home/omprakashg/.local/lib/python3.6/site-packages/django/db/models/expressions.py", line 8, in from django.db.models import fields File "/home/omprakashg/.local/lib/python3.6/site-packages/django/db/models/fields/init.py", line 11, in from django import forms File "/home/omprakashg/.local/lib/python3.6/site-packages/django/forms/init.py", line 9, in from django.forms.formsets import * # NOQA File "/home/omprakashg/.local/lib/python3.6/site-packages/django/forms/formsets.py", line 2, in from django.forms import Form ImportError: cannot import name 'Form' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/omprakashg/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/omprakashg/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 370, in … -
Internal Server Error connecting to Django database
I have a connection function built to write data to my database. Here's the connect function from views.py def _parse_body(body): body_unicode = body.decode("utf-8") return json.loads(body_unicode) @csrf_exempt def connect(request): body = _parse_body(request.body) connection_id = body['connectionId'] connect = Connection(connection_id=connection_id) connect.save() return JsonResponse({"message":"connect successfully"}, status=200) And the models from django.db import models # Create your models here. class Connection(models.Model): connection_id = models.CharField(max_length=255) class ChatMessage(models.Model): username = models.CharField(max_length=50) message = models.CharField(max_length=400) timestamp = models.CharField(max_length=100) Testing the connect api on postman and with curl returns a 500 internal server error like this: connect testing on postman Here's also the stacktrace: stacktrace -
openpyxl save to instance field django
I would like to insert an excel sheet file every time i submit a form using POST. File however, must to be previously generated in views and afterwards, inserted into an instance.field. Model: class Order(models.Model): ... attachment = \ models.FileField(\ _("Sheet"), upload_to='uploads/', max_length=100, blank=True, null=True) ... View: from openpyxl import Workbook from openpyxl.writer.excel import save_virtual_workbook class Order1(View): def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): obj = form.save(commit=False) #Creating sheet book = Workbook() sheet = book.active sheet['A1'] = 56 sheet['A2'] = 43 now = time.strftime("%x") sheet['A3'] = now #Calling model field instance - What im doing wrong here? obj.attachment = book.save("sample.xlsx") #Saving model instance obj.save() #Some return - required for AJAX return JsonResponse({"status": "OK"}) All saves besides attachemnt field. What im doing wrong here? -
ChoiceField in django doesnt show choices
im using django 3.0.3 and want to do simple CreateView with form from model. This is how it looks models.py class Recipe(models.Model): DINNER = 'Danie główne' SUPPER = 'Kolacja' DESSERT = 'Deser' STARTER = 'Przystawka' category_choices = ( (DINNER, 'Danie główne'), (SUPPER, 'Kolacja'), (DESSERT, 'Deser'), (STARTER, 'Przystawka'), ) title = models.CharField(max_length=200) # description = tinymce_models.HTMLField() recipe_category = models.CharField(max_length=30, choices=category_choices, default=DINNER) def get_absolute_url(self): return reverse('recipe:detail', kwargs={'id': self.id}) def __str__(self): return self.title forms.py class RecipeCreateForm(forms.ModelForm): class Meta: model = Recipe fields = ['title', 'recipe_category'] category_choices = {'recipe_category': 'Kategorie'} recipe_category = forms.ChoiceField(choices=category_choices, label='', initial='Danie główne', widget=forms.Select(), required=True) views.py class RecipeCreateView(CreateView): model = Recipe form_class = RecipeCreateForm success_url = 'home' template_name = 'main/add_recipe.html' def __init__(self, **kwargs): super().__init__(**kwargs) def form_valid(self, form): form.save() return HttpResponseRedirect(self.get_success_url()) def get_success_url(self): return reverse('homepage') and template add_recipe.html {% extends 'main/header.html' %} {% block content %} <head> </head> <body> <form method="POST"> {% csrf_token %} {{ form.as_p }} <button type="submit">SUBMIT</button> </form> </body> {% endblock %} Output is that it doesn't show choice field enter image description here I can't say where i'm missing something. In my other repo i have similar code that does work. Was trying to do some changes in template but doesnt give me anything. It is possible to use … -
In Django 3 how do I access my templates-directory using Javascript?
Maybe I am going about this the wrong way. I want to replace the content of the <nav>-element using jQuery.load() when the user clicks a certain <div>. But I am unable to access the html-file that I want to replace the content with. No matter what url I point the load to, the console always says: "GET http://127.0.0.1:8000/templates/nav_form.html 404 (Not Found)" My Javascript (jQuery) is: jQuery( '#EditIcon' ).on( 'click', function(){ jQuery( 'nav' ).load( 'templates/nav_form.html' ) }); So in the example I use the url templates/nav_form.html. When I replace this with ../templates/nav_form.html or ./templates/nav_form.html the message in the console remains the same telling me he cannot find http://127.0.0.1:8000/templates/nav_form.html -
Can I create a Kivy GUI for my Django Web App?
I have a Django web app which currently uses HTML templates with CSS styling. Fairly typical for a Django app. I've been looking to create a more animated GUI for this app and was looking to Kivy to do this. Is it possible to combine these two frameworks to coexist in the same app?