Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to validate plain HTML form fields in djano
I am a laravel developer and I am new to django. Everything went well in django until I started exploring forms. I want to use plain HTML forms and validate it using django forms validation but I am not getting proper reference or tutorial for doing so. I want some examples or help for validating plain HTML form fields in django. -
counting distinct values within a distinct value search on another field within same jango model
I am trying to pull some analytics from my django model table. So far I can count total values of a field and distinct values of a field. I also know how to create lists showing total values of fields within a distinct field. Now i'd like to count the distinct instances a field occurs within a list of already distinct values of a different field. Here's the table I am working with: | uid | cid | |-------|--------| | a | apple | | a | apple | | a | grape | | b | apple | | b | grape | | c | apple | | c | pear | | c | pear | | c | pear | So the result I am trying to provide is: cid: apple (distinct uid count: 3), cid: grape (distinct uid count: 2), cid: pear (distinct uid count: 1) and also: cid apple's distinct uid's: a, b, c cid grape's distinct uid's: a, b cid pear's distinct uid's: c So far I have been able to get distinct counts and lists like this: dist_uid_list = Fruit.objects.filter(client=user).values('uid').distinct() output >>> {'uid': 'a', 'uid': 'b', 'uid': 'c'} and this: dist_uid_count = … -
Accessing Windows located Firebird Database from Docker contained Django App
I am trying to access Firebird Database files located in C:/ drive from Docker Contained Django Application. I am using Python fdb package for accessing this. self.conn = fdb.connect( host='192.168.0.108', port=3050, database='/FIREBIRD_DB/TEST.FDB', user=usr, password=pswd) It generates error: Exception: The location of Firebird Client Library could not be determined. How can I access the machine's Firebird Database from Docker Contained Django app? -
MEDIA URL not loading on heroku gives 404
Hello my media files are not loading on heroku please correct me if i am wrong. i have used the following in the following files: settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mainapp.apps.MainappConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR,'jobhunter/static') ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' In urls.py i included the media root urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) on posts.html i wrote the below line: <img class="card-img-top" src="{{ MEDIA_URL }}{{ t.post_featured_image }}" alt="Card image"> Everything is working on local server but not on heroku. please tell me if i am missing something. -
Django Admin Dashboard showing incorrectly
When I open my Django Dashboard everything looks fine. But, when I click of the tables... This appears! I have no idea of what just happened. I'm still on project development so I don't mind loosing my current database. I literally have no idea of what just happened. -
Django System complete !What Next on deployment
This might seen a cliche question to senior developers.There are number of ways to deploy the django appalication online,AWS,heroku etc.But i want the best solution to deploy a app to be used by a small organization approximately 10 users!. I will appreciate any lead/information regading on this.I have reseached by i need solutions for engineers dealing with such activities.Thanks in advance. regards -
NoReverseMatch at /homeProva1/group/new/ Reverse for 'calendar' not found. 'calendar' is not a valid view function or pattern name
I've this error but i've not "calendar" when i create a CalendarGroups: NoReverseMatch at /homeProva1/group/new/ Reverse for 'calendar' not found. 'calendar' is not a valid view function or pattern name. I've this error also when i create new Event and new Calendar. In urls: path('homeProva1/', views.CalendarGroupList.as_view(), name='home'), #LISTA EDIFICI OK path('homeProva1/<int:pk>/calendars/', views.CalendarsOfGroupList.as_view()), #LISTA CALENDARI DI QUEL PK EDIFICIO OK path('homeProva1/<int:pk>/calendars/<int:pk1>/events/', views.EventsOfCalendarList.as_view()), #LISTA EVENTI DI QUEL PK CALENDARIO OK url('homeProva1/(?P<group_id>\d+)/calendars/(?P<calendar_id>\d+)/events/calendar/$', views.CalendarView.as_view(), name='calendar_view'), #CALENDARIO OK path('homeProva1/group/new/', views.group, name='group_newprova1'), #NUOVO GRUPPO OK path('homeProva1/<int:pk>/calendars/new/', views.calendarCreate, name='calendar_newprova1'), #NUOVO CALENDARIO OK path('homeProva1/<int:pk>/calendars/<int:pk1>/events/new/', views.event, name='event_newprova1'), #NUOVO EVENTO OK In views.py: @login_required def event(request, pk=None ,pk1=None): instance = Event() instance = Event(calendar_id=pk1) form = EventForm(request.POST or None, instance=instance) if request.POST and form.is_valid(): form.save() return HttpResponseRedirect(reverse('cal:home')) return render(request, 'cal/form.html', {'form': form}) @login_required def group(request): instance = CalendarGroups() form = CalendarGroupsForm(request.POST or None, instance=instance) if request.POST and form.is_valid(): form.save() return HttpResponseRedirect(reverse('cal:home')) return render(request, 'cal/form.html', {'form': form}) @login_required def calendarCreate(request, pk=None): instance = Calendar() #instance = Calendar() instance = Calendar(group_id=pk) form = CalendarForm(request.POST or None, instance=instance) #print (form['group']) if request.POST and form.is_valid(): #form['group'] = form.save() return HttpResponseRedirect(reverse('cal:home')) return render(request, 'cal/form.html', {'form': form}) In models: class CalendarGroups(models.Model): name = models.CharField(max_length = 155, blank=True, null=True, unique=True) def __str__(self): #self.name = name return str(self.name) … -
Python Django uses wrong query
I have a problem, to solve it I tried going into the shell but I couldn't find out the solution so I hope that you can help me. I'm importing my Model Images which contains an id and the image URL but I can't get it because of this error. The code: from recipes_database.models import Images Images.objects.all() And here the error: Traceback (most recent call last): File "F:\Developement\Projects\WhatToCookWeb\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "F:\Developement\Projects\WhatToCookWeb\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such column: Images.id The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "F:\Developement\Projects\WhatToCookWeb\venv\lib\site-packages\django\db\models\query.py", line 263, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "F:\Developement\Projects\WhatToCookWeb\venv\lib\site-packages\django\db\models\query.py", line 269, in __len__ self._fetch_all() File "F:\Developement\Projects\WhatToCookWeb\venv\lib\site-packages\django\db\models\query.py", line 1303, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "F:\Developement\Projects\WhatToCookWeb\venv\lib\site-packages\django\db\models\query.py", line 53, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "F:\Developement\Projects\WhatToCookWeb\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1154, in execute_sql cursor.execute(sql, params) File "F:\Developement\Projects\WhatToCookWeb\venv\lib\site-packages\django\db\backends\utils.py", line 98, in execute return super().execute(sql, params) File "F:\Developement\Projects\WhatToCookWeb\venv\lib\site-packages\django\db\backends\utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "F:\Developement\Projects\WhatToCookWeb\venv\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "F:\Developement\Projects\WhatToCookWeb\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "F:\Developement\Projects\WhatToCookWeb\venv\lib\site-packages\django\db\utils.py", line … -
Msgid in django not being recognized when it starts with percent symbol
Any msgid's that are created for translation do not seem to be recognized if it starts with %. The msgid and msgstr are created in the django.po file but when the code is run, the message remains untranslated. I am wondering if python-format is trying to recognize the % symbol as a placeholder, but I tried to escape the symbol and that still was not the solution. I am wondering if there is something else I am missing. -
How can I connect multiple models in Django
I`m a beginner in Django and want to create a system in the Django-models were a user can upload a course with a title and different Chapters which all can have multiple videos in them. As seen in this image. I thought about creating three models 1. Course with the course title 2. Chapter which has different videos in them 3. Video And here the video with a title of the video But I have no Idea how to create a connection between those three models, so that there can be multiple chapters in one course and multiple videos in one chapter. These are my first models (I just created them quickly): def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return 'user_{0}/{1}'.format(instance.user.id, filename) class video(models.Model): title = models.CharField(max_length=100) video = models.FileField(upload_to=user_directory_path) class course(models.Model): title = models.CharField(max_length=100) class chapter(models.Model): pass How should I adjust the models and create the connection to accomplish the system that I´m after? -
How to add labels for Django models.IntegerChoices
I have two IntegerChoices subclasses in one of my django Models that define ticket priorities for an api. I would like when the priority and statuses are rendered on my web page to show the label, but then when using the api to send the integer number corresponding with the label. This is my code so far: class Ticket(models.Model): class Statuses(models.IntegerChoices): OPEN = 2, 'Open' PENDING = 3, 'Pending' RESOLVED = 4, 'Resolved' CLOSED = 5, 'Closed' class Priorities(models.IntegerChoices): LOW = 1, 'Low' MEDIUM = 2, 'Medium' HIGH = 3, 'High' URGENT = 4, 'Urgent' priority = models.IntegerField(default=Priorities.LOW, choices = Priorities.choices) status = models.IntegerField(default=Statuses.OPEN, choices=Statuses.choices) I then try to access the label in my application via <b>Priority: </b> {{ ticket.priority.label }} <br> <b>Status:</b> {{ ticket.status.label }} But nothing shows up. It seems the Django docs for the new IntegerChoices class is very minimal, and is not clear about how the labeling function works. I also tried rendering the labels like so: OPEN = 2, _('Open') But then I got an error saying "name '_' is undefined" Any pointers in the right direction for what I need to do? -
How to Cancel Subscription created thought Checkout Session Stripe API
I have created a recurring product on stripe, and creating a checkout session and it's working fine and creating a subscription for me that i can see on the dashboard. this is my code checkout_session = stripe.checkout.Session.create( success_url=domain_url + 'success?session_id={CHECKOUT_SESSION_ID}', cancel_url=domain_url + 'cancelled/', payment_method_types=['card'], mode='subscription', line_items=[ { 'quantity': 1, 'price': 'price_1HLDRqCHEV6ur4mXq36yVF1D', } ] ) I want to provide a facility to user that they can cancle their subscription that they have made through checkout session, but it can be cancelled through subscription id only, but i am not getting any subscription id from the checkout session. How can i allow the user to cancle their subscription that they made through checkout session ? -
Django local memory caching not working on heroku
I have a requirement to authenticate user in my django-rest-framework application using SMS based OTP. For these I have created following API endpoint GET \otp - generate and send OTP and store it in cache POST \otp - validate OTP based on value store in cache Here's my code - from django.core.cache import cache # It is used just for debugging & logging purpose local_cache = {} class OTPView(APIView): def get(self, request): serializer = ContactSerializer(data=request.query_params) num = serializer.validated_data.get('contact_number') otp = generate_otp() cache.set(num, otp, 300) local_cache[num] = otp print('GET Cache is : ', local_cache) return Response('OTP Sent') def post(self, request): serializer = OTPSerializer(data=request.data) num = serializer.validated_data.get('contact_number') otp = serializer.validated_data.get('otp') print('POST Cache is : ', local_cache) otp_in_cache = cache.get(num) if otp_in_cache is None: return Response('No OTP or prev expired') elif otp == otp_in_cache: return Response('Success') else: return Response('Incorrect OTP') To persist the OTP across two requests I am using in-memory cache. It is working as expected in my local machine but not when deployed on Heroku. Here are the logs from heroku for reference - 2020-09-02T17:17:22.556785+00:00 app[web.1]: Number is 6666660008 and otp is 541609 2020-09-02T17:17:22.556798+00:00 app[web.1]: GET Cache is : {'6666660008': '541609'} 2020-09-02T17:17:22.558975+00:00 app[web.1]: 10.69.31.173 - - [02/Sep/2020:22:47:22 +0530] "GET /account/api/otp/?contact_number=6666660008 HTTP/1.1" … -
Keyerror in wizard form when passing data to step in Django
I'm new in Django and I'm doing a step form with Form Wizard. I have pass the data through steps but in the last step (step4) return a Keyerror for calling a variable 'categoriaPadre' that is in Step3. Please some help will be great! I attach what I have made: forms.py from django import forms from django.forms import ModelForm from django.utils.safestring import mark_safe from .models import * from .views import * class CustomMultipleChoiceField(forms.ModelMultipleChoiceField): def label_from_instance(self, obj): return mark_safe("<div class='image-option' style='background-image: url('%s');'></div>" % obj.imagen.url) class CustomChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return mark_safe("<div class='image-option' style='background-image: url('%s');'></div><div class='name'>%s</div>" % (obj.imagen.url, obj.name)) class PreStep1(forms.Form): name = forms.CharField(max_length=255) class PreStep2(forms.Form): categoriaPadre = CustomChoiceField(queryset=CategoriasPrePadre.objects.all(), widget=forms.RadioSelect) class PreStep3(forms.Form): def __init__(self, *args, **kwargs): c = kwargs['initial']['categoriaPadre'] print(c) self.categoria = CustomChoiceField(queryset=CategoriasPre.objects.filter(categoria_padre=c), widget=forms.RadioSelect) # NEED TO INCLUDE field categoria into "declared_fields"!!! self.declared_fields['categoria']=self.categoria # superclass constructor ought to be called only AFTER # including new field of class into "declared_fields" !!! super(PreStep3, self).__init__(*args, **kwargs) class PreStep4(forms.Form): def __init__(self, *args, **kwargs): c = kwargs['initial']['categoria'] print(c) self.slides = CustomMultipleChoiceField(queryset=Slides.objects.filter(categoria=c), widget=forms.CheckboxSelectMultiple) # NEED TO INCLUDE field categoria into "declared_fields"!!! self.declared_fields['slides']=self.slides # superclass constructor ought to be called only AFTER # including new field of class into "declared_fields" !!! super(PreStep4, self).__init__(*args, **kwargs) Here I create the … -
Method on django model to return the count of a foreign key
I want a method on a django model that returns the count of members in a foreignkey. I'd prefer it to be a class method (and not annotation) because I want to serialize it and send it via javascript without involving templates. Based on previous answers to similar questions, I believed the following sort of structure would work (some attributes deleted for the sake of simplicity): class Post(models.Model): likedby = models.ForeignKey('User', on_delete=models.CASCADE, null=True, blank=True, related_name='liked') def likes(self): return self.likedby_set.count() But when I run this I get AttributeError: 'Post' object has no attribute 'likedby_set'. Anyone know why this doesn't work? -
Django count extremely slow with full text search
I'm using Django SearchRank example to query a PostgreSQL database. The problem is that the final cursor results in very slow methods such as a simple count(). I need it to do pagination (I'm using Django El Pagination) I know that a similar issue was already asked here. However, I don't have here any ManyToMany relation. It's a simple text search copied from the documentation. articles = Article.objects.filter( jonal__slug__in = jornal_slug, publish_date__gte = from_date, publish_date__lte = to_date ) vector = SearchVector('body', weight='A') + SearchVector('title', weight='A') query = SearchQuery(termo) articles = articles.annotate(rank=SearchRank(vector, query)).filter(rank__gte=0.3).order_by('rank') -
Confusion about Imagefield
I am learning Django as a beginner. Commonly speaking(documentation-wise), is Imagefield for photos? What field is then for the image files? (dmg for example). Thank you. -
.delete() not working on a record called from signals.py Django
I am creating a Billing Panel. In the part where a duplicate Billing Address assigned to Order instance, it gets automatically deleted and the previous Billing Address gets assigned to the Order. While the previous Billing Instance gets Assigned to the Order but the duplicate Billing Address Instance is not getting deleted. I am a noob. There is not overridden delete method in the models. models.py :- class BillingAddress(models.Model): #Contains address and email and other info class Order(models.Model): billingAddress = billingAddress = models.ForeignKey(BillingAddress, null=True,on_delete=models.SET_NULL ) signals.py :- @receiver(post_save, sender=Order) def dont_save_if_all_fields_matching(sender, instance, created, **kwargs): if created: currentOrder = instance previousBilling = BillingAddress.objects.filter(user=currentOrder.user, firstname=currentOrder.billingAddress.firstname, lastname=currentOrder.billingAddress.lastname, phonenumber=currentOrder.billingAddress.phonenumber, address1=currentOrder.billingAddress.address1, address2=currentOrder.billingAddress.address2, city=currentOrder.billingAddress.city, country=currentOrder.billingAddress.country, state=currentOrder.billingAddress.state, pincode=currentOrder.billingAddress.pincode ) if len(previousBilling) > 0: currentBillingId = currentOrder.billingAddress.id currentOrder.billingAddress = previousBilling[0] currentOrder.save() BillingAddress.objects.get(id=currentBillingId).delete() #The above code is not working -
Using pythonOCC's render function in Django
I have a Django application and I'm using pythonOCC package in it. I have to display the 3D .stl, .stp, .igs files in my template. I have tried to use render() function which in threejs_renderer.py file in the package. Here is my view: from OCC.Extend.DataExchange import read_step_file from OCC.Display.WebGl import x3dom_renderer from OCC.Core.BRep import BRep_Builder from OCC.Core.TopoDS import TopoDS_Shape from OCC.Core.BRepTools import breptools_Read def index(request): shape = read_step_file('test.stp') my_renderer = x3dom_renderer.X3DomRenderer() my_renderer.DisplayShape(shape) my_renderer.render() return render(request, 'index.html') When I call the render() function, the following outputs appear on my vscode console and since flask app created by pythonocc instead of django starts running in localhost, my index.html is never rendered. The output when I call the render function: ** Model Complete Check List ** Check:1 -- Entity (n0:id) 5:#14 Type:CURVE_STYLE Parameter n0.2 (curve_font) not an Entity Check:2 -- Entity (n0:id) 6:#15 Type:CURVE_STYLE Parameter n0.2 (curve_font) not an Entity Check:3 -- Entity (n0:id) 7:#16 Type:CURVE_STYLE Parameter n0.2 (curve_font) not an Entity Check:4 -- Entity (n0:id) 8:#17 Type:CURVE_STYLE Parameter n0.2 (curve_font) not an Entity Check:5 -- Entity (n0:id) 9:#18 Type:CURVE_STYLE Parameter n0.2 (curve_font) not an Entity Check:6 -- Entity (n0:id) 10:#19 Type:CURVE_STYLE Parameter n0.2 (curve_font) not an Entity ## x3dom webgl renderer - … -
pg_dump: fails for contents of table
So I tried to run this command heroku pg:pull postgresql-objective-94323 dbname --app appname This is the error that is thrown back pg_dump: dumping contents of table "public.table_name" events.js:287 throw er; // Unhandled 'error' event ^ Error: write EPIPE at WriteWrap.onWriteComplete [as oncomplete] (internal/stream_base_commons.js:92:16) Emitted 'error' event on Socket instance at: at errorOrDestroy (internal/streams/destroy.js:108:12) at Socket.onerror (_stream_readable.js:729:7) at Socket.emit (events.js:310:20) at errorOrDestroy (internal/streams/destroy.js:108:12) at onwriteError (_stream_writable.js:463:5) at onwrite (_stream_writable.js:484:5) at internal/streams/destroy.js:50:7 at Socket._destroy (net.js:677:5) at Socket.destroy (internal/streams/destroy.js:38:8) at WriteWrap.onWriteComplete [as oncomplete] (internal/stream_base_commons.js:93:12) { errno: 'EPIPE', code: 'EPIPE', syscall: 'write' } -
Django adding CSS classes to field
I am trying to add an error class to fields of a each form in a formset if a custom clean method detects errors. This does look to do the trick, I load the page, and the field does have the error class in it. but when in the template I add a custom filter to add a form-control class, everything falls apart. # in my inlineformset: def clean(self, *args, **kwargs): if any(self.errors): errors = self.errors return ## 1) Total amount total_amount = 0 for form in self.forms: if self.can_delete and self._should_delete_form(form): continue amount = form.cleaned_data.get('amount') total_amount += amount if total_amount> 100: for form in self.forms: form.fields['amount'].widget.attrs.update({'class': 'error special'}) raise ValidationError(_('Total amount cannot exceed 100%')) And, here is my code for the custom filter: @register.filter(name = 'add_class') def add_class(the_field, class_name): ''' Adds class_name to the string of space-separated CSS classes for this field''' initial_class_names = the_field.css_classes() ## This returns empty string, but it should return 'error special' class_names = initial_class_names + ' ' + class_name if initial_class_names else class_name return the_field.as_widget(attrs = {'class': class_names,}) And, in my template: {# {{ the_field|add_class:"form-control"}} #} #<- This adds the form-control, but removes the other classes added in the clean method {{ the_field }} … -
Django: How can I set form instance as a variable which was defined inside the HTML page?
So my blog has posts and comments. I want the users to be able to edit the comment through a BOOTSTRAP MODAL that opens inside the same page when you click the edit button. But I'm actually facing a problem, now there is a for loop inside the html page where I defined the comment variable : {%for comment in comments%} <button type="button" class="btn btn-warning btn-sm" data-toggle="modal" data- target="#Edit{{comment.id}}Modal">edit test</button> {%endfor%} Code at Views.py : post = Post.objects.get(slug=slug) comments = post.comment_set.all() if request.method == 'POST': editcommentform = CommentForm(request.POST, instance=comment) if editcommentform.is_valid(): editcommentform.save() else: editcommentform = CommentForm(instance=comment) now in my views.py I cannot actually set the instance to comment because I get an error of "comment is not defined" My question is how can i set the instance to comment while it's only defined inside the for loop in the HTML page? Sorry if it may sound unclear or weird, I am new to the field. -
Sending websockets message from inside of Consumer's connect() closes the connection
While tracking down the root cause for this question I stumpled upon an issue with using self.send() from inside the connect() of a AsyncWebsocketConsumer. It closes the websocket instead of sending the message: import json from uuid import UUID from channels.generic.websocket import AsyncWebsocketConsumer from myapp.models import AnalysisResult class AnalysisConsumer(AsyncWebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.analysis_id = self.scope['url_route']['kwargs']['analysis_id'] self.analysis_group_name = "analysis_{}".format(self.analysis_id) async def connect(self): await self.channel_layer.group_add(self.analysis_group_name, self.channel_name) # Setting up this whole channel / websocket connection takes a while. Thus, we need # to send an initial update to the client to make sure a (too) fast analysis result # doesn't get lost while we've been busy here. # Problem: This is DISCONNECTING instead of sending the message. await self.send(text_data=json.dumps({ 'progress_percent': 100, 'status_text': "Done already." })) await self.accept() async def disconnect(self, code): await self.channel_layer.group_discard(self.analysis_group_name, self.channel_name) Is that expected behavior and I shouldn't try to send something via the websocket from inside the Consumer's connect() method? Or should that be working? -
update django model instance - save() method not working
I'm trying to update a model field using save(), and the change is not being saved. I have no idea why, can someone help? below is an abbreviated version of the code: models.py class Mandate(models.Model): user_id = models.ForeignKey( User, on_delete=models.SET_NULL, editable=True, null=True, ) id = models.CharField(primary_key=True, max_length=32) mode = models.CharField(max_length=16) ... some other fields def __str__(self): return str(self.id) my_module.py def sync_mandate_locally(customer_id, mandate_id): c = Customer.objects.get(id=customer_id) mandate = client.customer_mandates.with_parent_id(customer_id).get(mandate_id) m, created = Mandate.objects.get_or_create(id=mandate_id, user_id=c.user_id) m.mode = mandate.get('mode') print(f"1. {m.mode = }") m.save() m, created = Mandate.objects.get_or_create(id=mandate_id, user_id=c.user_id) print(f"{created = }") print(f"2. {m.mode = }") output: || 1. m.mode = 'pindakaas' || created = False || 2. m.mode = '' -
Django Modal Create & Update No Jquery
i am trying to implementing the create and update through a pop up modal, i have my code in place however, the code basically will start with create and if the object is created it will take the used to the update and will pull the data in the Modal for updating. the problem is that once the form is submitted in the create view the user is logged out but data is created in the DB and when clicking on the button it should load the data from DB for update but that not happening. the codes are as below: below is my concept code : models.py: class Startup ( models.Model ) : author = models.OneToOneField ( User , on_delete = models.CASCADE ) startup_name = models.CharField ( max_length = 32 , null = False , blank = False ) class Score_Appeal(models.Model): appeal_score = models.ForeignKey(Startup, on_delete = models.CASCADE) appeal_evaluator = models.ForeignKey(User, on_delete = models.CASCADE) appeal = models.CharField ('Appeal', max_length = 100 , null = False , blank = False , choices = Choice.EVALUATION , default = '' ) appeal_comment = models.TextField(max_length = 100, blank = True) views.py: view.py: @login_required @inv_required def global_list(request): startup = Startup.objects.all() return render(request, 'inv_template/global_list.html', {'startup': startup}) …