Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use django multiple settings config, is that OK or fine? I mean recommended way
I want django settings like spring boot *.yml settings way to develop, default settings could set, and active settings could overwrite default settings. I trid many ways, finally find this way blow, I want get some recommendations or advices. refer to Django multiple settings I create project.settings module and add multiple settings file, and change the manage.py like: import os import sys from mysite.settings import settings if __name__ == '__main__': os.environ.setdefault('DJANGO_SETTINGS_MODULE', settings.ACTIVE_SETTINGS) In default settings.py file add ACTIVE_SETTINGS for manage.py to import. default setting file mysite/settings/settings.py like: import datetime import os ACTIVE_SETTINGS = 'mysite.settings.dev_settings' more default settings..... In develop dev_settings.py file set default settings refer to #custom-default-settings in mysite/settings/dev_settings.py like: from django.conf import settings from mysite.settings import settings as default # use this could set default settings to active setting settings.configure(default, DEBUG=True) more dev settings..... Setting django in this way could realize only change one setting ACTIVE_SETTINGS to develop and default settings could also set if ACTIVE_SETTINGS file not set, I've read many blogs, no other way could better than this. -
TextField onchange feature with Django CMS Wizard, Form and App Config
I am developing a website using django CMS. In their built-in app config for Pages (for example), they have a field wherein we can input a slug for the page we create. By default, while you type the page title, the slug textfield also types in a value automatically in a slug format, like below: I want to learn how to do this in my custom app configs as well as on my CMS wizards. Reason being, we will have non-technical staff who will later be given permission to add events and news. Adding events and news requires providing a slug which will be used later for URL routing. Since they are non-technical personnel, it is not ideal for them to provide the slug manually i.e. they might forget to add a hyphen or misspell some words. Thus, it would be safer to just automatically fill the slug field with default value as you type the page title. If anyone can share a piece of code or share the concept on how to do this as simple and straightforward as possible it would greatly help. Cheers! -
MySQL row-column-value format to python dictionary
I am relatively new to Python (and Django) and have some data in a MySQL database in a row-column-value format Django Model "UserParameters": user_id | param | value ----------------------------------- 123 | param_1 | xxx 123 | param_2 | yyy 123 | param_3 | zzz 123 | param_4 | aaa 123 | param_5 | bbb 123 | param_6 | xxx ... ... 456 | param_1 | sse 456 | param_2 | aca 456 | param_3 | cce 456 | param_4 | dwe 456 | param_5 | cck 456 | param_6 | aq1 ... ... 789 | param_1 | zzz ... I'm trying to get this data in MySQL into a dictionary in the following format: users = { 123: {'param_1': 'xxx', 'param_2': 'yyy', 'param_3': 'zzz', 'param_4': 'aaa', 'param_5': 'bbb', 'param_6': 'xxx'}, 456: {'param_1': 'sse', 'param_2': 'aca', 'param_3': 'cce', 'param_4': 'dwe', 'param_5': 'cck', 'param_6': 'aq1'}, 789: {'param_1': 'zzz', ..... } So far, I've tried users = {} users_params = UserParameters.objects.all().values() for u in users_params: users[u['user_id']].add(u['param'], u['value']) This gives me a key error. Any idea what I could be doing wrong? Thank you! -
Wagtail PASSWORD_REQUIRED_TEMPLATE is not overriding the default login
I'm building a global login page for Wagtail. The setting for PASSWORD_REQUIRED_TEMPLATE isn't working. In fact, i can't find n example where it actually does work which makes me think that I don't understand what it's supposed to do. When I add; PASSWORD_REQUIRED_TEMPLATE = 'utils/auth/password-required.html' to the settings file it does not catch the login form and use my custom form. Is this a know issue? -
How to remove Ck editor tag in django rest framework
I am using Django rest framework. The CkEditor tags I've used for the web appear in the API part. How do I remove these tags from the API I had not used Ckeditor before, I was using the Django TextField field models.py ''' class Lesson(models.Model): ... lesson_content = RichTextField( verbose_name=_('Ders İçeriği'), blank=True ) ... ''' seriaizer.py ''' class LessonSerializer(serializers.ModelSerializer): class Meta: model = Lesson fields = (...,'lesson_content',...) ''' output(Json Data) {"id":1,"user":2,"lesson_name":"Microprocessors","lesson_content":"Merkezi işlem birimi (CPU) : CPU kaydedicileri , Aritmetik ve lojik birim, Durum bayrakları, Mikroemirlerin icrası, Mikroprogramlama ve kontrol birimi , CPU bacakları. Bellekler: ROM, RAM, PROM, EPROM ve E2PROM bellekler. Kod çözücüler ve belleklerin CPU'ya bağlanışı. Paralel Giriş/Çıkış : Programlı G/Ç, kesmeli G/Ç, Doğrudan bellek erişimli G/Ç. Seri Giriş/Çıkış. Mikrobilgisayarların programlanması: Kaynak ve amaç programlar. Assembly dili ve assembler direktifleri. Bellek adresleme yöntemleri. CPU emir takımı. Gerçek CPU'lar. Mikrobilgisayar sistem tasarımı. Uygulamalar. .","lesson_content_file":"http://192.168.2.7:8000/media/user%20ulutas%40ktu.edu.tr/microprocess.pdf","lesson_notes":" \r\n\r\nYazıcı, R., 1998, Mikrobilgisayar Donanım ve Yazılımı, KTÜ Yayınları, Trabzon, 345 s.\r\n\r\nBrey, B., B., 1984, Microprocessor/Hardware Interfacing and Applications, Merrill, 414 p.\r\n\r\nLeventhal, L., A., 1979, Z80 Assebly Language Programming, Osborne/McGraw-Hill, 612 p.\r\n\r\nUffenbeck, J., 1985, Microcomputers and Microprocessors: The 8080, 8085, and Z80 Programming, Interfacing, and Troubleshooting, Prentice-Hall, 670 p.\r\n\r\n ","lesson_notes_file":"http://192.168.2.7:8000/media/user%20ulutas%40ktu.edu.tr/microprocess_qUAazMf.pdf"} & nbsp; \ r \ n \ r … -
How to pass variable as ARG or KWARG in my get_success_url
I have been working all afternoon to try and pass a variable to a get_success_url to show the correct record after I process an UpdateView. I am using class based views, and I am trying to update a record and then show the corresponding update record in a different view. However, when I am passing the pk, it works but it's not the right one. Essentially, here is the code in question... def get_success_url(self): return reverse_lazy('Book:create_new_author_detail', kwargs={ 'pk' : self.object.pk }) The above would work fine and does in many scenarios. However, in this case, I am trying to pass a specific pk that does not align with this particular updateview. I have tried something like.... def get_success_url(self): return reverse_lazy('Book:create_new_author_detail', kwargs={ 'pk' : self.object.new_author.pk }) Perhaps something like.... def get_success_url(self): return reverse_lazy('Book:create_new_author_detail', kwargs={ 'pk' : self.object.pk, 'new_author' : self.new_author.id }) Would work? I can get the pk using this code, just not the right one. I want to reference new_author.id so that the reverse_lazy picks the right pk. Thanks in advance for any thoughts. -
How to fix 'NoReverseMatch at /' error on Django app?
I'm new to Django and I'm trying to just build a basic application to work off in the future. I keep getting an error saying "NoReverseMatch at/ Reverse for 'about' not found. 'about' is not a valid view function or pattern name." I've searched for other people with the same issue and it seems their issues used an older version of Django and they used different functions from what I'm using. I'm using a book called Hello Web App by Tracy Osborn, which simplifies everything, and all the code I've found dealing with a similar problem seems far more complicated than what I've done so far. I've tried changing my views.py file to request the base.html file instead of the index.html file which didn't work. I've double checked my syntax on all files, including the html file. And, I've made sure the urls.py file matched up exactly. I still keep getting the same error. here is my urls.py file from django.contrib import admin from django.urls import path from django.views.generic import TemplateView from condata import views urlpatterns = [ path('', views.index, name='home'), path('about/', TemplateView.as_view(template_name='about.html'), name='about'), path('contact/', TemplateView.as_view(template_name='contact.html'), name='contact'), path('admin/', admin.site.urls), ] views.py from django.shortcuts import render # Create your views here. … -
App crashed , deployment Heroku error in Django
I'm deploying my first Django app on Heroku and i get this error: 2019-06-17T22:02:04.615398+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=carlosdelgado1.herokuapp.com request_id=210a779e-59ba-46c3-af78-e60215244798 fwd="24.55.161.197" dyno= connect= service= status=503 bytes= protocol=https 2019-06-17T22:34:14.393752+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=carlosdelgado1.herokuapp.com request_id=cc7678e9-c3ec-4b97-9a34-383b6f6f0a4e fwd="24.55.161.197" dyno= connect= service= status=503 bytes= protocol=https this is whats in my Procfile: web: gunicorn porfolio.wsgi i did these import in the wsgi.py file: import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "kloudless.settings") from django.core.wsgi import get_wsgi_application from dj_static import Cling application = Cling(get_wsgi_application()) here is the github link to the blog project: https://github.com/Poucarlos/portfolio I'm trying to display my blog in Heroku to see it when I access it -
Error in production No module named 'django.db.migrations.migration'
recently I pulled from my git the new version of the project, unfortunately I made a mistake and my settings.py file was completly overwrite. I fix it but when I run my apache server and tried to make a request in the logs I found this: [Mon Jun 17 17:31:02.934215 2019] [wsgi:error] [pid 29830] [remote 200.116.66.129:52114] from .migration import Migration, swappable_dependency # NOQA<br/> [Mon Jun 17 17:31:02.934240 2019] [wsgi:error] [pid 29830] [remote 200.116.66.129:52114] ModuleNotFoundError: No module named 'django.db.migrations.migration' I looked in this other question: Updating Django - error: 'No module named migration' and tried every posibility unsuccessfully. What else should I do to fix this? -
How to create checkboxes with the values of model instances created by users
I want to create forms with checkboxes in them which values of these checkboxes is a model instance created by users. Here is my SessionModel: class SessionModel(models.Model): starting_time = models.TimeField() . . Imagine that I have several instances of this model with various starting_times. and I have another model which is: class TimeModel(models.Model): time = models.TimeField() now i want to select the required instances of SessionModel and update them. But the problem is that I want to have a form with checkboxes with the values of TimeModel.time to grab the instances in SessionModel with the starting_time same as selected TimeModel.time but I don't know how to create these checkboxes should I use dynamic forms or is there any other way I can do this? -
How do I add information from javascript variables to Django ModelForm input?
I am building a web application using Django. The page shows a large leaflet map, in which users can select one out of several layers. I want users to be able to select a layer, click on the map and add a note to that location and that layer. I've created a model form, which holds the note itself. This works fine, and saves to my database. However, I need to also include the currently selected layer and mouse-click-location, which is readily available as a JS variable. How do I pass this on in Django? My views.py holds the following: if request.method == 'POST': form = MapNoteForm(request.POST) if form.is_valid(): form.save() else: form = MapNoteForm() And forms.py: class MapNoteForm(forms.ModelForm): note = forms.CharField() class Meta: model = MapNote fields = ('note',) Finally, the relevant section of the template: map.on('click', function (e) { var MapNote = L.popup(); var content = '<form method="post"> {% csrf_token %} {{form}} <br> <button type="submit"> Save</button>' MapNote.setContent(content); MapNote.setLatLng(e.latlng); //calculated based on the e.layertype MapNote.openOn(map); }) I'm kind of looking to reverse the workings of the Django-view, trying to pass something from the template to Django, instead of vice versa. What would be the best approach here? -
Django templatetag does not expand text properly if it contains double brackets
I'm using a templatetag to expand some TextFields at my Django application (see code below). I'm using the templatetag like this at my template.html: {% load readmore %} ... <h4>{{ user.about|readmore:300|safe|linebreaks }}</h4> this is the actual templatetag which contains the functionality to expand the textfield at my template.html: readmore.py from django import template from django.utils.html import escape from django.utils.safestring import mark_safe import re register = template.Library() readmore_showscript = ''.join([ "this.parentNode.style.display='none';", "this.parentNode.parentNode.getElementsByClassName('more')[0].style.display='inline';", "return false;", ]); @register.filter def readmore(txt, showwords=15): global readmore_showscript words = re.split(r' ', escape(txt)) if len(words) <= showwords: return txt # wrap the more part words.insert(showwords, '<span class="more" style="display:none;">') words.append('</span>') # insert the readmore part words.insert(showwords, '<span class="readmore">... <a href="#" onclick="') words.insert(showwords+1, readmore_showscript) words.insert(showwords+2, '">more</a>') words.insert(showwords+3, '</span>') # Wrap with <p> words.insert(0, '<p>') words.append('</p>') return mark_safe(' '.join(words)) readmore.is_safe = True The problem with this templatetag is the following: If the TextField I'm applying this templatetag onto contains double brackets the "button" to expand the Textfield (labled as 'more' - See: words.insert(showwords+2, '">more') at code above) get's placed somewhere inside the TextField I display on my side... Which again looks quite stupid because it should be at the bottom, to show the user that there is more to read-on. can … -
Swagger provide correct render of POST method API from serializer, but not for DELETE method
Our project is using Django, Django-Rest-Framework, and drf_yasg to document our API with swagger. I created a serializer, and I'm using it with my POST method. everything works well, all the fields are present on my swagger page. I created a delete method using the same serializer and the swagger documentation is showing as parameters to the API only the first group of fields. I tried to use @swagger_auto_schema( method='post', operation_description="POST /Rules/list/", responses={200: listResponseSerializer()}, ) @swagger_auto_schema( @swagger_auto_schema(responses={200: listResponseSerializer()}) method='delete', operation_description="DELETE /Rules/list/", responses={200: listResponseSerializer()}, ) @action(detail=False, methods=['post', 'delete']) and have a single method. both, the post and delete methods are immediately absent from the documentation page. and when using @swagger_auto_schema(responses={200: listResponseSerializer()}) Post method is working, but not the delete method. this capture shows the good results from POST method, where all the fields are presents in the API documentation. filters, parameters, and others. https://1drv.ms/u/s!AvljzERK5-K2akGS8l9zHs8yEtw?e=3QmMe9 With DELETE, it shows only the filters and ignores all the other fields present in the serializer. https://1drv.ms/u/s!AvljzERK5-K2a-x4dqsPCMELUr0?e=LY6jbj Hope someone can help me with this one. I'm struggling for a couple of days now with it. I don't catch what I'm missing or what piece of the integration between django and swagger I don't understand, and need … -
How to Display Div When Checkbox Is Checked
I want to display the hidden div when the checkbox is selected. Currently, when the checkbox is selected, the div remains hidden. Perhaps the nested structure of the divs is causing issues? page.html <div class="field"> <label class="label">Opportunity Information:</label> <div class="field"> <div class="control"> <label class="checkbox"> <input type="checkbox" name="ware_type" id="ware_type" onchange="showHiddenField()">Hardware/Software:</a> </label> </div> </div> <div class="field"> <div class="field"> <input class="input" name="estimate_id" id="estimate_id" type="text" placeholder="Estimate ID" style="display: none;"> </div> </div> </div> script.js function showHiddenField(currentObject) { var inputDiv = $(currentObject).parent().next(); if ($(currentObject).is(":checked")) { $(inputDiv).toggle('show'); } else { $(inputDiv).hide(); } } -
I want to see Google Map and its nearby places in my Django project [on hold]
I want to use Google map to show nearby hospital, pharmacy. How can i do? it It is better to have a resource or tutorial. -
In DRF, how can I serialize the data retrieved from an ad-hot route?
I have the 3 models below: #Appointment class Appointment(models.Model): doctor = models.ForeignKey( Doctor, on_delete=models.CASCADE, related_name='doctor_appointment') patient = models.ForeignKey( Patient, on_delete=models.CASCADE, related_name='patient_appointment') scheduled = models.DateTimeField(auto_now_add=True) # Doctor class Doctor(models.Model): user_id = models.TextField(unique=True) first_name = models.CharField(max_length=100, blank=False) last_name = models.CharField(max_length=100, blank=False) # Patients class Patient(models.Model): user_id = models.TextField(unique=True) first_name = models.CharField(max_length=100, blank=False) last_name = models.CharField(max_length=100, blank=False) and their 3 respective serializers: # Patient Serializer class PatientSerializer(serializers.ModelSerializer): # contract_number = serializers.PrimaryKeyRelatedField(queryset=Contract.objects.all()) class Meta: model = Patient fields = '__all__' # Doctor Serializer class DoctorSerializer(serializers.ModelSerializer): tariff = serializers.DecimalField( source='DoctorTariff.amount', max_digits=6, decimal_places=2) class Meta: model = Doctor fields = '__all__' # Appointment Serializer class AppointmentSerializer(serializers.ModelSerializer): doctor = serializers.CharField(source='Doctor.user_id') patient = serializers.CharField(source='Patient.user_id') service_provided = serializers.CharField(source='ServiceProvided.service') upcoming = serializers.SerializerMethodField() class Meta: model = Appointment fields = '__all__' For my Appointment model, I've specified an ad-hoc route that will show the upcoming appointment: class AppointmentViewSet(viewsets.ModelViewSet): queryset = Appointment.objects.all() serializer_class = AppointmentSerializer @action(detail=False, url_path='upcoming/(?P<user_id>[^/.]+)') def upcoming_appointment(self, request, user_id=None): try: queryset = Appointment.objects.filter(patient__user_id=user_id).\ select_related('patient', 'doctor').values('scheduled', doctor_first_name=F('doctor__first_name'), doctor_last_name=F('doctor__last_name'), specialty=F('doctor__specialty'), doctor_address=F('doctor__address')) #serializer = AppointmentSerializer(queryset, many=True) # if serializer.is_valid(): except Appointment.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) # If I use serializer.data instead of queryset I get an error return Response(queryset, status=status.HTTP_200_OK) This code works fine, meaning that If I hit the upcoming endpoint I can see … -
Best way to load static images in Django from root directory
I am working on a project in Django 2.2 and I am having a problem loading static images. I followed a tutorial that suggests a media directory in the root of the project. After that, I configured settings as suggest as shown below: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' The urls.py of the project as shown below: urlpatterns = [ path('admin/', admin.site.urls), path('', include('base.urls')) ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And this is the base.urls file that has the pages with the images I am trying to load: urlpatterns = [ path('', views.index, name='tedfield-home'), path('faqs/', views.faqs, name='tedfield-faqs'), path('contact/', views.contact, name='tedfield-contact'), path('about/', views.about, name='tedfield-about'), ] I am loading static images used by the website. These images are loading well for the home page, but when I navigate to a page like /about, the images fail to load. On checking, the link loaded is http://127.0.0.1:8000/about/media/images/brands/brand-2.png which has the about instead of the link: http://127.0.0.1:8000/media/images/brands/brand-2.png which is the actual link that loads the images. The code that I am using for the html template is: <img src="media/images/icons/area.png" alt=""> I have also tried using a static directory on the root folder … -
Why is user query triggering TypeError?
I have a CustomUser model in a Django app that I'm trying to query, but the query raises TypeError: all() missing 1 required positional argument: 'self' What I'm trying to accomplish is addressed in several posts here, including this one. >>> from django.contrib.auth import get_user_model >>> User = get_user_model() >>> userList = User.objects.all() Here's my user model: class CustomUser(AbstractUser): username = models.CharField(max_length=11, blank=True, default= 'newUser', verbose_name="User Group") email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager # add additional fields in here display_name = models.SlugField(max_length=50, unique=True) phone = models.CharField(max_length=14, blank=True, help_text="XXX-XXX-XXXX") def __str__(self): return self.display_name Instead of the expected queryset I get the error referencing the missing 'self' argument. The solutions I've found here for that error don't seem to work; clearly I'm missing something. -
Return the other model's field as a response to POST request
In my models.py there are two models: class Genre(models.Model): genre_id = models.CharField(max_length=10) name = models.CharField(max_length=40) information = models.CharField(max_length=120) def __str__(self): return self.name class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=100) genre = models.ForeignKey(Genre, on_delete=models.CASCADE) def __str__(self): return self.title They are serialized: class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ('title', 'author', 'genre') class GenreSerializer(serializers.ModelSerializer): class Meta: model = Genre fields = ('name', 'information') and ViewSets are created for each: class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer class GenreViewSet(viewsets.ModelViewSet): queryset = Genre.objects.all() serializer_class = GenreSerializer What I'd like to do is: Sending a POST request to books/ endpoint. Sent data has to contain existing genre ID, it won't be saved to the database otherwise (it's done by default already). Receiving information from the Genre model as a response. Let me give a short example: I'm sending this JSON: { "title": "Hercules Poirot", "author": "Agatha Christie", "genre": 1 } Instead of repeated request from above I receive something like this: { "genre": "crime story" } How to do this? -
Problems making migrations with mysqlclient whit Django virtual enviroment
I want to make a mysql database connection using django, and I have downloaded the mysqlclient packages to do this, but when I use python manage.py makemigrations it throws me the next error: 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 "/Users/paulmirve/anaconda3/envs/myDjangoEnv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/paulmirve/anaconda3/envs/myDjangoEnv/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/Users/paulmirve/anaconda3/envs/myDjangoEnv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/paulmirve/anaconda3/envs/myDjangoEnv/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/Users/paulmirve/anaconda3/envs/myDjangoEnv/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/Users/paulmirve/anaconda3/envs/myDjangoEnv/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/paulmirve/anaconda3/envs/myDjangoEnv/lib/python3.7/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Users/paulmirve/anaconda3/envs/myDjangoEnv/lib/python3.7/site-packages/django/contrib/auth/base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "/Users/paulmirve/anaconda3/envs/myDjangoEnv/lib/python3.7/site-packages/django/db/models/base.py", line 117, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/Users/paulmirve/anaconda3/envs/myDjangoEnv/lib/python3.7/site-packages/django/db/models/base.py", line 321, in add_to_class value.contribute_to_class(cls, name) File "/Users/paulmirve/anaconda3/envs/myDjangoEnv/lib/python3.7/site-packages/django/db/models/options.py", line 204, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "/Users/paulmirve/anaconda3/envs/myDjangoEnv/lib/python3.7/site-packages/django/db/__init__.py", line 28, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "/Users/paulmirve/anaconda3/envs/myDjangoEnv/lib/python3.7/site-packages/django/db/utils.py", line 201, … -
How fix to upload image from bootstrap modal form in django
I can not find the information how to load image through django modal form. How to upload a file through a django modal form? my file models.py class Meal(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) name = models.CharField(max_length=500) short_description = models.CharField(max_length=500) image = models.ImageField(upload_to='meal_images/', blank=False) price = models.IntegerField(default=0) def __str__(self): return self.name my file form.py class MealForm(forms.ModelForm): class Meta: model = Meal exclude = ("restaurant",) What needs to be added to views.py to process image loading views.py def restaurant_add_meal(request): data = dict() if request.method == "POST": form = MealForm(request.POST, request.FILES) if form.is_valid(): form.save() data['form_is_valid'] = True meals = Meal.objects.all() data['meal_list'] = render_to_string('meal_list.html',{'meals':meals}) else: data['form_is_valid'] = False else: form = MealForm() context = { 'form': form } data['html_form'] = render_to_string('restaurant/add_meal.html', context, request=request) return JsonResponse(data) Modal form add_meal.html {% load crispy_forms_tags %} <form method="POST" data-url="{% url 'restaurant-add-meal' %}" class="create-form" enctype="multipart/form-data"> {% csrf_token %} <div class="modal-header bg-blue"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true" class="text-white">&times;</span> </button> <h4 class="modal-title text-center text-white" >Add Meal</h4> </div> <div class="modal-body"> {{form|crispy}} </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-pink">Add Meal</button> </div> </form> ajax code that handles the form. I can not understand what is missing here. plugin.js $(document).ready(function(){ $('.show-form').click(function(){ $.ajax({ url: '/restaurant/meal/add', type: 'get', dataType:'json', beforeSend: … -
Unable to set auth_user model primary key as foreign key in my app models.py
I am trying to create a blog app with models.py I want to set auth_user model primary key as foreign key to my model in blog app.After adding the appropriate code i am getting the following error? from django.db import models from django.conf import settings # Create your models here. class Post(models.Model): title=models.CharField(max_length=100) desc=models.TextField() date=models.DateTimeField(auto_now=True) author=models.ForeignKey("settings.AUTH_USER_MODEL", on_delete=models.CASCADE) ERRORS: blog.Post.author: (fields.E300) Field defines a relation with model 'User', which is either not installed, or is abstract. blog.Post.author: (fields.E307) The field blog.Post.author was declared with a lazy reference to 'blog.user', but app 'blog' doesn't provide model 'user'. -
How to query by joining a Django Model with other, on a non unique column?
I have the following models in my models.py file in my django project from django.contrib.auth.models import AbstractUser from django.db import models from django.conf import settings class CustomUser(AbstractUser): pass # add additional fields in here class PDFForm(models.Model): pdf_type=models.IntegerField(default=0) pdf_name=models.CharField(max_length=100,default='') file_path=models.FileField(default='') class FormField(models.Model): fk_pdf_id=models.ForeignKey('PDFForm', on_delete=models.CASCADE,default=0) field_type=models.IntegerField(default=0) field_page_number=models.IntegerField(default=0) field_x=models.DecimalField(max_digits=6,decimal_places=2,default=0) field_y=models.DecimalField(max_digits=6,decimal_places=2,default=0) field_x_increment=models.DecimalField(max_digits=6,decimal_places=2,default=0) class Meta: ordering= ("field_page_number", "field_type") class UserData(models.Model): fk_user_id=models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,default=0) field_type=models.IntegerField(default=0) field_text=models.CharField(max_length=200,default='') field_date=models.DateField() Here is how the models are related 1) a pdfform contains a pdf form and path for it on the file system 2) A pdfform has multiple FormFields in it. Each field has attributes, and the specific one under discussion is field_type 3)The UserData model has user's data, so one User can have multiple rows in this table. This model also has the field_type column. What I am trying to query is to find out all rows present in the Userdata Model which are present in the FormField Model ( matched with field_type) and that are of a specific PDFForm. Given that the Many to Many relationship in django models cannot happen between no unique fields, how would one go about making a query like below select a.*, b.* from FormField a, UserData b where b.fk_user_id=1 and a.fk_pdf_id=3 and a.field_type=b.field_type … -
Django - Determine model fields and create model at runtime based on CSV file header
I need to determine the best approach to determine the structure of my Django app models at runtime based on the structure of an uploaded CSV file, which will then be held constant once the models are created in Django. I have come across several questions relating to dynamically creating/altering Django models at run-time. The consensus was that this is bad practice and one should know before hand what the fields are. I am creating a site where a user can upload a time-series based csv file with many columns representing sensor channels. The user must then be able to select a field to plot the corresponding data of that field. The data will be approximately 1 Billion rows. Essentially, I am seeking to code in the following steps, but information is scarce and I have never done a job like this before: User selects a CSV (or DAT) file. The app then loads only the header row in (these files are > 4GB). The header row is split by ",". I use the results from 3 to create a table for each channel (columns), with the name of the field the same as the individual header entry for that … -
What technology to use to create a real-time collaborative table
I run a very distributed help desk. One of the issues that we are running into is that most of the tools out there for technology documentation have a reasonably high barrier of entering data into them (anything more than 20 seconds to navigate and get into is an issue. What I'd love to try to innovate for fun is this - - Single web form that has a few simple columns. - As people add rows (take notes, think of it as a tech diary) these will update on the other tech's screens, our NOC screens, etc. - Some of the fields should be able to be pre-populated from the database. For example, we definitely have all of the data available to us from our network management systems, so if a tech starts typing in a server name we'd want for it to start popping up suggestions, like google does. Sorry for being so basic -- we are infrastructure guys and don't even know where to start speccing this out. We have 100% no problem paying someone to build this for us, but we'd love to have some understanding of who/what/how/why are. We wouldn't even know where to start …