Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can custom values be passed from a DRF ModelViewSet to a permissions class?
I've set up a custom permissions class to be reused from multiple views, in an app where some users have ownership-like rights on behalf of other users: class IsOwnerLike(permissions.BasePermission): def has_permission(self, request, view): if ( user_is_owner(request.user, request.data["owned_by"]) | user_is_owner_like(request.user, request.data["owned_by"]) ): return True return False This works as expected for one ModelViewSet. However, for legacy reasons, different requests coming in to different views may not have an "owned_by" data element -- it may be called "owned", "owner", "created_by", etc. -- and therefore I can't reuse this custom permission as written. What is the correct way to abstract things at the viewset, to normalize data being passed to my custom permissions class? Can this be done, or should I be thinking about handling these permissions differently? -
Another custom template tag registration issue in django
I know there are similar issues, I tried to learn from them, but still doesn't work. I am trying to register custom template tag in django. I have following error: django.template.library.InvalidTemplateLibrary: Module order.templatetags.order_tags does not have a variable named 'register' mytemplate.html: {% load order_tags %} settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "order", 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], "libraries" : { "order_tags" : "order.templatetags.order_tags", }, }, }, ] order_tags.py: from django.template import Library register = Library() @register.simple_tag def create_var(data): return str(data) Structure: order/ templates/... templatetags/ __init__.py order_tags.py forms.py models.py views.py I tried shutting down the server. I also tried adding "order.templatetags", in INSTALLED_APPS in settings.py. I also confirmed that order_tags.py loads without an error: python manage.py shell >>> from order.templatetags import order_tags What am I missing? Thanks! Django==2.2.6 Python==3.7.4 -
Passing variable through URL in Django
I'm facing some trouble to pass variables trough templates/URL/view in my index.html. This is my URLs: urlpatterns = [ path('admin/', admin.site.urls), path('users/', include('django.contrib.auth.urls')), path('', include('dma.urls')), ] app_name = 'root' urlpatterns = [ path('<int:category_id>', views.index, name='index'), path('buy/', views.buy, name='buy'), path('sell/', views.sell, name='sell'), path('stock/', views.stock, name='stock'), path('debtor/', views.debtor, name='debtor'), path('debtor/<str:buyer>', views.debt, name='debt'), path('financial/', views.financial, name='financial'), ] My view: def index(request, category_id): products = Buy.objects.filter(sell__buyer__isnull=True) categories = Category.objects.all() context = {'products': products, 'categories': categories} return render(request, 'index.html', context) My template: {% for category in categories %} <a href="{% url 'root:index' category.id %}" class="list-group-item">{{ category.name }}</a> {% endfor %} I'm not sure but the problem might be in URL code. The template is printing exactly the categories names in the {{ category.name }} Error: Using the URLconf defined in home.urls, Django tried these URL patterns, in this order: admin/ users/ <int:category_id> [name='index'] buy/ [name='buy'] sell/ [name='sell'] stock/ [name='stock'] debtor/ [name='debtor'] debtor/<str:buyer> [name='debt'] financial/ [name='financial'] ^media/(?P<path>.*)$ The empty path didn't match any of these. -
Whitenoise giving FileNotFound after deleting file in staticfiles directory
I changed my static files storage to whitenoise's CompressedManifestStaticsFileStorage. I ran collectstatic. I then saw duplicate files in the staticfiles directory, the second one having a filename ending with a random sequence of numbers and letters. I thought it was not useful, so I deleted it. Ever since then, whitenoise has refused to work again. Every time I collectstatic, it says that that particular file I deleted is missing. I reinstalled whitenoise, but nothing changed. However, when I changed back to Django contribs static file storage, it works fine. I have tried everything that I have seen online but it doesn't help (adding the option --clear, changing code in the src: storage.py etc. of the Django staticfiles app. What can I do? Also,is there a way to edit the staticfiles.json (or is it manifest.json) of whitenoise for the project Thank you very much -
How add data in django serializer only once
I have a django serializer as below, class VideoSerializer(CustomSerializer): class Meta: model = apis_models.Video fields = '__all__' def to_representation(self, video): data = super().to_representation(video) return { 'ordering': { 'video': { "label": "Order By", "options": { "Newest First": '-upload_date', "Oldest First": 'upload_date', "Views (High)": "views", "Views (Low)": "-views" } } }, 'body': data, } Which prints the output as below. The "ordering" key appears in each element. I need it to be appear only once at top. I believe using to_representation would be the best way to do it since it is a constant value. But I am not sure how do I get it only once. How could I get it? Please help. { "count": 339, "next": "http://10.0.0.238:8000/videos/?page=2", "previous": null, "results": [ { "ordering": { "video": { "label": "Order By", "options": { "Newest First": "-upload_date", "Oldest First": "upload_date", "Views (High)": "views", "Views (Low)": "-views" } } }, "body": { "id": 6142, "source": { "id": 5, "name": "kpopdeepfakes_net", "domain": "https://kpopdeepfakes.net", } } }, { "ordering": { "video": { "label": "Order By", "options": { "Newest First": "-upload_date", "Oldest First": "upload_date", "Views (High)": "views", "Views (Low)": "-views" } } }, "body": { "id": 6153, "source": { "id": 5, "name": "kpopdeepfakes_net", "domain": "https://kpopdeepfakes.net", } } … -
dynamically created button wont trigger function
I have a drop down list to which I append buttons by js. Everything works fine but I couldn't get my buttons to perform their onclick action. here is the code which generates the buttons: function (data) { $("#pop-up").css("display", "none"); $("#pop-up").empty(); $("#pop-up").append("<p class=search-top>titles</p>"); if (data.title4) { $("#pop-up").append("<b onmousedown='event.preventDefault()' onclick='showtime('pop-button4')' id=pop-button4>"+data.title4+"</b>") } if (data.title3) { $("#pop-up").append("<b onmousedown='event.preventDefault()' onclick='showtime('pop-button3')' id=pop-button3>"+data.title3+"</b>") } if (data.title2) { $("#pop-up").append("<b onmousedown='event.preventDefault()' onclick='showtime('pop-button2')' id=pop-button2>"+data.title2+"</b>") } if (data.title1) { $("#pop-up").css("display", "block"); $("#pop-up").append("<b onmousedown='event.preventDefault()' id=pop-button1>"+data.title1+"</b>")} I tryed both js and jquery but couldn't get them to work, the last function I tryed is: $('#pop-button1').on('click', function(){ console.log("here") }); It does nothing at all. -
can´t save multiple files in Django
I have created a bucle to upload multiple files in django, but when I try to upload them, only the data of the files are saved in the django database, and only one of the files is uploaded is uploaded to my local service, I would like to know what is the problem, because it is very difficult to upload one file at a time when there are thousands. This is my bucle: `My model class Document(models.Model): letraDoc= models.CharField(max_length=100, null=True, blank=True) nameDoc = models.CharField(max_length=1000, null=True, blank=True) extensionDoc = models.CharField(max_length=100, null=True, blank=True) document = models.FileField(upload_to='documents') document_carpeta= models.ForeignKey(Carpetas, on_delete= models.CASCADE) document_pruebita= models.IntegerField(blank=True, null=True) def __str__(self): return self.nameDoc My view class documentCreate(CreateView, LoginRequiredMixin): model = Document template_name = 'documentos/document-create.html' fields = ['document','document_carpeta'] def form_valid(self, form): if self.request.FILES: archivos = self.request.FILES.getlist('document') for archivo in archivos: docName = archivo.name docNameArray = docName.split('.') docLetter = docNameArray[0] newDoc = Document( document = form.instance.document, nameDoc = docName, letraDoc = docNameArray[0], extensionDoc = docNameArray[len(docNameArray) - 1], document_carpeta = form.instance.document_carpeta ) if not str(docLetter) in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']: messages.warning(self.request, f'No se pudo subir el archivo {docName}, solo subir archivos con iniciales a-h') else: newDoc.save() return HttpResponseRedirect(reverse('carpetasDetail', kwargs= {'pk':newDoc.document_carpeta.pk})) My HTML <div class="modal fade show" id="docCreate" … -
Django Class based UpdateView with Form for Multiple Uploaded Files
I have to questions in regards to the problem currently facing: Is it best practice in django to overwrite the post method in the CreateView? If it isn't do you write a form _valid function on the CategoryFullForm or in the CreateView and how would it look? The CreateView currently works great, but want to make sure there isnt a better way to do this. If this is best practice, how would you override the get function in the UpdateView so you would be able to edit the files that relate to the instance being uploaded and even add an additional File? Open to other ways to accomplish this task as well. models.py ############ CATEGORY MODEL ################ class Category(models.Model): category_id = models.AutoField(primary_key=True) name = models.CharField(max_length=100, null=True, blank=True) est_pr_sqft = models.FloatField(blank=True) est_duration = models.IntegerField(blank=True) preceding_job = models.CharField(max_length=100, blank=True) category_notes = models.CharField(max_length=250, blank=True) category_slug = models.SlugField(max_length=100, unique=True, null=False) author = models.ForeignKey(User, on_delete=models.CASCADE, default=1) date_posted = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('category-detail', kwargs={'slug': self.category_slug}) def save(self, *args, **kwargs): if not self.category_slug: self.category_slug = slugify(self.name) return super().save(*args, **kwargs) class CategoryFiles(models.Model): category_id = models.ForeignKey(Category, on_delete=models.CASCADE) document = models.FileField(upload_to="attachments",null=True,blank=True) uploaded_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) def delete(self, *args, **kwargs): self.document.delete() … -
Dash bootstrap components not showing
I wanted to have progress bar in my Django project but it is not showing on page. I have installed django-dash and dash-bootstrap-components. Code: import dash_html_components as html import dash_bootstrap_components as dbc from django_plotly_dash import DjangoDash app = DjangoDash("Example", add_bootstrap_links=True) app.layout = html.Div(dbc.Progress(value=100)) and template {% load plotly_dash %} <div class="{% plotly_class name="Example" %}"> {% plotly_app_bootstrap name="Example" %} </div> -
Ajax + Django, display user input in url
For some reason after moving my stuff around, the url is no longer displaying like so ... 127.0.0.1:800/?Item=test or 127.0.0.1:800/?Item=testing+more+words My Ajax is working as intended after a lot of trial and error, but now I've lost that little piece and I'm not sure why. It's now static http://127.0.0.1:8000/ even after clicking the submit button. I'm not sure what that is called, so I'm hoping someone could help me out here. This is the code I have. <form autocomplete="off" action="" method="GET"> <div class="autocomplete"> <input id="myInput" type="text" name="Item" placeholder="Enter Item"> </div> <input type="submit" id="submitBtn" value="Search"> </form> <div class="chart-container"> <canvas id="myChart"></canvas> </div> <script type="text/javascript"> var endpoint = 'api/chart/data/' var dataset = [] var labels = [] $('#submitBtn').click(function(e){ var item = $('#myInput').val(); e.preventDefault(); $.ajax({ url: endpoint, method: "GET", dataType: "text", success: function(){ $.ajax({ method: "GET", url: endpoint, data:{ 'item': item, }, success: function(data){ console.log(item) labels = data.labels dataset = data.dataset var ctx = document.getElementById('myChart').getContext('2d') var chart = new Chart(ctx, { type: 'line', data: { labels: labels, datasets: [{ label: item, data: dataset }] }, }) }, }) } }) }) </script> -
Classified ads website on Django framework
I am finalizing my classified ads website. Everything is working fine. How do I link everything together now that the project is almost complete. When I click on the home page button be directed there, because I can only navigate through pages when I write the URL link. I want the links and the buttons to be connected so as to have one wholesome project. The project is done on the Django framework. -
Filter queryset on a foreignkey
It might be not new to all and need your expert guidance. I am trying to filter a column on a django-table2. Note I have not used django-filter here. class Group(models.Model): title = models.CharField(blank=True) class Control(models.Model): published = models.charField(auto_now=False) group = models.ForeignKey(Group, on_delete=models.CASCADE) Now I am trying to filter in views.py as below table = ControlTable(Control.objects.all().order_by('-published').filter( group__in=form['contact'].value(), ) Issue is this is working fine, but when selecting '-----' from dropdown then its showing blank table instead of all the values. Again if I change the query filter as below table = ControlTable(Control.objects.all().order_by('-published').filter( Group__title__iexact=form['contact'].value(), ) then throwing error Cannot resolve keyword 'Group' into field. Could you please guide me on this? -
Unable install Pillow
I tried installing pillow in the following ways: $~ pip install Pillow $~ python3 -m pip install Pillow $~ python -m pip install Pillow But none of these worked. How can I install pillow? -
uploading video with vimeo and django
i am creating a function to let users submit video's of their product on an e commerce project. The users upload the video through a django form with filefield, I then use django to take the video and send it to Vimeo's API for upload. This is currently working however i have noticed it is really slow. When the user presses submit on the form, with a video of 1 min legnth, their waiting over 15 seconds just to have the form successfully submited. I am trying to make a solution that will be able to scale to a large number of users and video uploads, while being cost effective at the same time. I have posted the code below, if anyone can think of a quicker way to do this, please let me know. Thanks The video passed to this function is the TemporaryUploadedFile from the form. def video_upload(video, product_pk): #Initial sending, get an upload link url = 'https://api.vimeo.com/me/videos' headers = { 'Authorization': 'bearer %s' % settings.VIMEO_TOKEN, 'Content-Type' : 'application/json', 'Accept' : 'application/vnd.vimeo.*+json;version=3.4'} data = {'upload' :{ 'approach' : 'tus', 'size' : video.size}, 'name' : str(product_pk)} r = requests.post(url, headers=headers, data=json.dumps(data)) if r.status_code == 200: uri = r.json()['uri'] # … -
Reverse Foreign Key attribute whithin current model
Here a question which I cannot solve after having read various posts. I have two models where one is linked by a foreign key to another one as follow: class Brewery(models.Model): name= models.CharField(max_length=100, null=False, blank=False) class Beer(models.Model): brewery = models.ForeignKey('Brewery', on_delete=models.SET_NULL, null=True, blank=False) name= models.CharField(max_length=100, null=False) image = models.ImageField(upload_to='photos/', blank=True) I would like to store pictures of Beer in a folder which contains the name of the related Brewery. For example, let's say I have the following: Brewery: id = 1, name = "John_Martin" Beer: id = 1, brewery = 1, name = "Dominus" Then I'd like that upload_to points to "John_Martin/Dominus". Is that possible? Thank you in advance, OF1418 -
I get MerchantGroupFilter' object is not iterable using django-filter
I'm trying to set up a simple filter using django-filter. I've done this before and it worked, so not able to figure out whats gone wrong this time. The error I get is MerchantGroupFilter' object is not iterable. models.py class MerchantGroup(models.Model): created = models.DateTimeField(null=False, blank=False, default=timezone.now) name = models.CharField(max_length=100, null=False, blank=False) ledger = models.ForeignKey('journal.Ledger', on_delete=models.PROTECT, null=True, blank=True) filters.py import django_filters from monzo.forms import DateTypeInput from journal.models import Ledger from .models import MerchantGroup # from monzo.models import # Duplicate of the above? class MerchantGroupFilter(django_filters.FilterSet): class Meta: model = MerchantGroup # Fields list needs to be present for FilterSet to work fields = ['ledger'] views.py @login_required def merchantgroups_show_all(request): merchant_groups = MerchantGroupFilter(request.GET, queryset=MerchantGroup.objects.all()) #merchant_groups2 = paginator.get_page(page) return render(request, 'monzo/merchantgroups_show_all.html', {'merchant_groups': merchant_groups,}) Traceback Environment: Request Method: GET Request URL: http://localhost/monzo/merchantgroups/show/all/ Django Version: 3.0.5 Python Version: 3.8.2 Installed Applications: ['monzo', 'rest_framework', 'django.contrib.humanize', 'journal', 'adminsortable2', 'widget_tweaks', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed 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'] Template error: In template C:\Users\Philip\CodeRepos\Acacia2\templates\template.html, error at line 0 'MerchantGroupFilter' object is not iterable 1 : <!doctype html> 2 : <html lang="en"> 3 : <head> 4 : <!-- Required meta tags --> 5 : <meta charset="utf-8"> 6 : <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> 7 … -
Problem with running IBM DB2 connection in Django for Windows
I'm new to Django and am trying to connect two databases. One is a .sqlite3 DB and the other is a DB2 database. `DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'DB_2': { 'ENGINE': 'ibm_db_django', 'NAME': 'DB_Name', 'USER': 'my_username', 'PASSWORD': 'my_pass', 'HOST': 'external_host', 'PORT': '50001', 'PCONNECT': True, }, }` My sqlite3 DB works fine, but when I try to run python manage.py test or python manage.py migrate I get the following error: django.core.exceptions.ImproperlyConfigured: 'ibm_db_django' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' In looking at the IBM website, it looks like I need to install ibm_db_django, which I've done. I feel like it has to do with how my engine is defined, like I need it to point somewhere else on the computer. If that is that case, I've no clue where it's supposed to be. Could someone please help point me in the right direction? Thank you very much. -
Converting a string to a list and seperate each element
So I have a use case in which I enter indexes and descriptions which belong to a round. I created a JS function that allows me to enter these indexes and descriptions. When I strip the data from the post request I get the following data: ['0,This is a testround', '1,This is a new testround'] I want to split this data so that I can seperate the 0 in an index variable and the following description "This is a testround" in a description variable. Please note that the description can only contain comma's. A possible solution could be to split the string on a comma and use str[0] for the index and the other parts for the description but to me this would look like an ugly solution. What should I do? I use the following JS to save the rounds to a playerdata div from which i extract the list above (in which items is the list with the index and description) function item_checkbox(items,n) { return ` <input type="checkbox" style="display:none;" name="${itemList[n]}" value="${items}" checked> ` } function add_to_itemData(items, n) { itemDataEl = document.getElementById(itemData[n]) itemDataEl.innerHTML = itemDataEl.innerHTML + item_checkbox(items, n) } Thanks for any help in advance -
How To Access Key/Value Attributes Within A Crispy Forms Template
Ive made a custom template for a field in a crispy form but am stuck with two things. 1 - I know how to access the fields label (field.id_for_label), but dont know how to access a key/value pair (I would expect field.key, field.val, but they dont work). 2 - I am wanting to add col-3 to each of the key/value pairs in the field (which I can do) but also want to surround each block of four with <div class='row'> </div> tags so the align neatly, but cannot find a way to do this within the template. form.py TOPICS = ( ('ANI', 'Animals'), ('ART', 'Art'), ('COM', 'Communication'), ('CRI', 'Crime'), ('CUL', 'Culture/Society'), ('EDU', 'Education'), ('ENT', 'Entertainment'), ('ENV', 'Environment') [..cont..] ) preferred_topics = forms.MultipleChoiceField(choices=TOPICS, required=False, widget=forms.CheckboxSelectMultiple()) def __init__(self, *args, **kwargs): super(NeedsAnalysisForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( 'lessons_per_week', CustomCheckbox('preferred_topics'), 'teacher', 'grade',) ) custom_template.html {% load crispy_forms_field %} <div id='div_id_preferred_topics' class="form-group"> <label for='id_preferred_topics'>{{ field.label }}</label> <div class> {% for field in form.preferred_topics %} <div class='col-3 custom-control custom-checkbox custom-control-inline'> <input type='checkbox' class='custom-control-input' name='preferred_topics' id='{{ field.id_for_label }}' val=<!-- ??value?? -->>> <label class='custom-control-label' for='{{ field.id_for_label }}'><!-- ??key?? -->></label> </div> {% endfor %} </div> </div> Thank you. -
Why 'request.user.username' return a random string?
when I use this code: <h5>WELCOME!{{ request.user.username }}</h5> It returns a random string rather than the user name I want. How could I solve this problem? -
Django doesn't want to show media files
I'm trying to output an image which i save like this: product_image = models.ImageField(blank = True, upload_to='images') My seetings.py looks like: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Also here is urls.py: urlpatterns = [ path('admin/', admin.site.urls), url(r'^$', include('store.urls')), url(r'^', include('store.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Query is like simple implemetation of ORM, but i tried it on ORM also def index(request): products = DAO.get_all_products() return render(request, 'store/index.html', locals()) HTML: <img src="{{product.product_image}}" class="img-responsive watch-right" alt=""/> And it doesn't work, i don't see any image, and {{product.product_image}} shows me images/pic13.jpg in browser. But i can see this image in /admin Error: Not Found: /images/pic13.jpg How to fix this issue? This page is situated is App called store, urls.py and settings.py are in main app -
Wagtail Tags ui for other models
In Wagtail there are tags that are super easy to use. Their UI input adds a new entry with every comma or tab keystroke. From a UI perspective, it is a great way to add list items, it works the same way as Tags does at the bottom of asking questions on stackoverflow. This example visualizes a similar UI new Vue({ el: '#app', vuetify: new Vuetify(), data () { return { chips: ['Programming', 'Playing video games', 'Watching movies', 'Sleeping'], items: ['Streaming', 'Eating'], } }, methods: { remove (item) { this.chips.splice(this.chips.indexOf(item), 1) this.chips = [...this.chips] }, }, }) // Working Example https://codepen.io/redhaus/pen/WNQLozL? editable=true&editors=101%3Dhttps%3A%2F%2Fvuetifyjs.com%2Fen%2Fcomponents%2Fchips%2F Is there a way to utilize this UI input on Stuct blocks or even orderable models that have simple single input fields, rather than the traditional + needed to add additional entries. I am finding issues with Wagtail Tags such as being able to prefetch them to limit queries, so I am hoping to get the same UI functionality with better rest performance from traditional models. -
Django - Interrupt StreamingHttpResponse
So basically I am performing streaming on my Django application and I am performing some image detection in it. So I would like to stop streaming when I detect a specific object in my streaming. Could you please advise on how I may proceed ? view.py def get_frame(request): camera = cv2.VideoCapture(0) while True: _, img = camera.read() decodedObjects = decode(img) for obj in decodedObjects: result = obj.data.decode('ascii') for obj in ImgScan.objects.filter(code = result): utilisateur = obj.username logging.debug(utilisateur) logging.debug("SUCCESS") matched = True imgencode = cv2.imencode('.jpg', img)[1] stringData = imgencode.tostring() yield (b'--frame\r\n'b'Content-Type: text/plain\r\n\r\n' + stringData + b'\r\n') del (camera) @gzip.gzip_page def dynamic_stream(request, stream_path="video"): try: return StreamingHttpResponse(get_frame(request), content_type="multipart/x-mixed-replace;boundary=frame") except: return render(request=request, template_name="main/cata.html") print("ERROR") In my template I have an image calling the dynamic_stream function, thus streaming within it. template.html <h1>Video Streaming</h1> <img class="img-responsive img-fluid" src="{% url 'main:videostream' stream_path='video' %}"> I am completely lost from here and can't seem to find a way to notify the template so I can either hide the img field when the object is detected in streaming or maybe at least be able to raise an error in the dynamic_stream() function so by handling it I can render another page as workaround. Thanks a lot. -
Foreign Keys are not getting assigned - Django
i am new to this, any recommendations are accepted, my main problem is that i have some foreign keys that are getting assigned in my database. As you can see the last 4 models are related to the patient model through a Foreign Key, these are the fields that are not getting assigned in my project. Models class Patient(models.Model): Codigo = models.CharField(max_length=20,default=None,null=False) Nombres = models.CharField(max_length=100,null=False) Apellidos = models.CharField(max_length=100,null=False) Fecha_Nacimiento = models.DateField() Numero_Telefonico = models.CharField(max_length=200,default=' ') Email = models.CharField(max_length=256,unique=True,blank=True,default=' ') Genero = models.ForeignKey(Gender,on_delete=models.DO_NOTHING,default=None,null=True) Nacionalidad = models.ForeignKey(Nationality,on_delete=models.DO_NOTHING,default=None,null=True) Estado_Civil = models.ForeignKey(CivilStatus,on_delete=models.DO_NOTHING,null=True) Ocupacion = models.CharField(max_length=200) Lugar_de_Procedencia = models.CharField(max_length=200) Lugar_de_Residencia = models.CharField(max_length=200) def __str__(self): return self.Nombres + ' ' + self.Apellidos class MedicalInfo(models.Model): Expediente = models.CharField(max_length=500,blank=True) Sangre = models.ForeignKey(BloodType,on_delete=models.DO_NOTHING,default=None,null=True) Peso = models.FloatField() Estatura = models.FloatField() Alergia = models.ForeignKey(Allergies,on_delete=models.CASCADE,default=None,null=True) Observacion = models.CharField(max_length=500,default= ' ',null=True) Paciente = models.OneToOneField(Patient,on_delete=models.CASCADE,default=None,blank=True,null=True) class InsuranceInfo(models.Model): Seguro = models.ForeignKey(InsuranceCompany,on_delete=models.DO_NOTHING, default=None,blank=True,null=True) Tipo_de_Poliza = models.ForeignKey(Policy,on_delete=models.DO_NOTHING,default=None,blank=True,null=True) Numero_Poliza = models.IntegerField(default=None,blank=True,null=True) Vencimiento = models.DateField(default=None,blank=True,null=True) Paciente = models.OneToOneField(Patient,on_delete=models.CASCADE,default=None,blank=True,null=True) class Relatives(models.Model): Parentesco = models.ForeignKey(Family_relation, on_delete=models.DO_NOTHING,default=None,blank=True,null=True) Nombre = models.CharField(max_length=100,blank=True) Apellido = models.CharField(max_length=100,blank=True) Telefono = models.CharField(max_length=100,blank=True) Correo = models.EmailField(blank=True) Nacimiento = models.DateField(blank=True,null=True) Pariente = models.OneToOneField(Patient,on_delete=models.CASCADE,default=None,blank=True,null=True) def __str__(self): return self.Nombre + ' ' + self.Apellido class Background(models.Model): Padecimiento = models.CharField(max_length=200) Control = models.CharField(max_length=200) Medicamento = models.CharField(max_length=500) Paciente = models.OneToOneField(Patient,on_delete=models.CASCADE,default=None,blank=True,null=True) These are my forms, … -
Error while calling a Post method in Django templates
I am working on an web application using Django. I am trying to access the views in django using the post method in javascript which is called when a button is clicked The HTML button which I used in Django templates is <a id = "{{ f.food_id }}" class="btn btn-info" href="#myModal" onclick="addCart(event);" class="trigger-btn" data-toggle="modal"> Add To Cart</a> The above button calls the below java script function <script> //This function should call the python function (addToCart) in django views.py which is used to add items to the cart function addCart(event) { var me = event.currentTarget var food_id = me.getAttribute("id"); alert(food_id); //The below url "/food/addToCart/(?P<item_id>\d+)" is linked to the addToCart funtion in the views.py $.post("/food/addToCart/"+food_id+"/", //This post method isn't working {}, function(data, status){ }); } </script> In the above function I'm trying to access the below addToCart method in views.py using the above post method def addToCart(request,item_id): try: cartTrail = Cart.objects.get(user_id=request.user.username,food_id=str(item_id)) cartTrail.quantity += 1 cartTrail.save() print("already present",cartTrail) except Cart.DoesNotExist: items = FoodItem.objects.filter(food_id=item_id)[0] cartItem = Cart.objects.create(user_id=request.user.username, res_id=items.restaurant.username.username, food_id=item_id,food_name=items.food_name,price=items.price) cartItem.save() return JsonResponse({'data':'Added'}) My urls.py contains the below url : url(r'^addToCart/(?P<item_id>\d+)/$',views.addToCart,name="addToCart"), My problem is that the post method isn't working when the addToCart is clicked and due to this def addToCart(request,item_id): function is not being …