Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
css and js is not working in blog detail page wagtail
enter image description here CSS and JS is not working in blog detail page -
Django to heroku deployment issue
While attempting to deploy my django project, I am running into a strange error: There is a dependency that I didn't use, and uninstalled, that is still trying to load with requirements.txt during the build. I have since uninstalled all of the dependencies, removed it from requirements.txt, run makemigrations and migrate, and yet it still tries to load it, which crashes the deployment. PyGObject is the dependency. workflow: Procfile - web: gunicorn solarsystem.wsgi ran - pip3 freeze > requirements.txt the dependency is no longer showing after uninstalling it. however during build: Collecting PyGObject remote: Downloading PyGObject-3.42.0.tar.gz (716 kB) remote: Installing build dependencies: started remote: Installing build dependencies: finished with status 'done' remote: Getting requirements to build wheel: started remote: Getting requirements to build wheel: finished with status 'done' remote: Preparing wheel metadata: started remote: Preparing wheel metadata: finished with status 'done' ... ERROR: Failed building wheel for PyGObject ... ERROR: Could not build wheels for PyGObject which use PEP 517 and cannot be installed directly and here is my requirements.txt: asgiref==3.3.4 autopep8==1.5.7 boto3==1.17.108 botocore==1.20.108 click==8.0.1 cm-rgb==0.3.6 cycler==0.10.0 dj-database-url==0.5.0 Django==3.2.3 django-appconf==1.0.4 django-compressor==2.2 django-heroku==0.3.1 django-libsass==0.9 django-material==1.9.0 django-materializecss-form==1.1.17 django-on-heroku==1.1.2 django-sass-processor==1.0.1 gunicorn==20.1.0 hidapi==0.10.1 Jinja2==3.0.1 jmespath==0.10.0 kiwisolver==1.3.1 libsass==0.21.0 MarkupSafe==2.0.1 matplotlib==3.4.3 mpld3==0.5.5 numpy==1.21.2 Pillow==8.3.1 psutil==5.8.0 psycopg2==2.9.1 … -
How to add event for checked row
I'm using django and it's printing a table. Currently, using the latest jquery script, clicking the Transfer Selected Rows button moves the selected rows to the second table. But I'm managing a server and I want the second table to be saved and visible to users. Should I create another class model to store the second table? Alternatively, when moving to the second table for the checked row, I would like to change the select column to name column and add the user name currently logged in in bulk. Another method I thought of is to apply a different color to each checked row and save it to the server. That is, I have 2 teachers and I want to assign them to students. Help.. <table id="student-list" class="maintable"> <thead> <tr> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Name</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Register Date</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Age</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Sex</th> <th class="text-black text-center text-nowrap bg-secondary font-weight-bold sticky-top-custom">Select</th> </tr> </thead> <tbody> {% for student in students %} <tr> <td>{{ student.name }}</td> <td>{{ student.register_date|date:'Y-m-d' }}</td> <td>{{ student.age }}</td> <td>{{ student.sex }}</td> <td><input type="checkbox"></td> </tr> {% endfor %} </tbody> </table> <input type="button" value="Transfer Selected … -
Unable to save in different database in django?
I am trying to save data into different database but its not saving and not giving any errors. settings.py I have two database mypage and ringi. mypage is set to default. DATABASE_ROUTERS = ['app_kanri.router.myrouter'] DATABASE_APPS_MAPPING = { 'ringi':'ringi_db' } DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mypage', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306', }, 'ringi_db':{ 'ENGINE': 'django.db.backends.mysql', 'NAME': 'ringi', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306', } } models.py class Approvallog(models.Model): # id = models.IntegerField(primary_key=True) cat_name = models.CharField(max_length=100,default=None,blank=True) cat_id = models.IntegerField(default=None,blank=True) cat_subid = models.IntegerField(default=None,blank=True) status = models.IntegerField(default=None,blank=True) user = models.CharField(max_length=100,default=None,blank=True) app_root = models.IntegerField(default=None,blank=True) app_step = models.IntegerField(default=None,blank=True) comment = models.TextField(default=None,blank=True) created = models.DateTimeField(default=None,blank=True) modified = models.DateTimeField(default=None,blank=True) class Meta: app_label = 'ringi' db_table = "approvallogs" router.py class myrouter: def db_for_read(self, model, **hints): if model._meta.app_label == 'ringi': return 'ringi_db' else: return None def db_for_write(self, model, **hints): if model._meta.app_label == 'ringi': return 'ringi_db' else: return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'ringi' or \ obj2._meta.app_label == 'ringi': return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == 'ringi': return db == 'ringi_db' return None This is how I am saving Appr_log = Approvallog() Appr_log.cat_name=str(data2['cat_name']) Appr_log.cat_id=data2['cat_id'] Appr_log.cat_subid=data2['cat_subid'] Appr_log.status=data2['status'] Appr_log.user=data2['user'] Appr_log.save(using="ringi_db") I tried to print(Appr_log.save(using="ringi_db")) and … -
I'm doing a get request with fetch in a django app, it works in development but not in production and cannot get the problem
The application is deployed on heroku. When I run the program on my machine it works fine, but in production I get different errors. In Google Chrome in the console I get the following error: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 In Firefox the error in the console is as follows Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data I received the following report from Sentry: Exception gaierror: [Errno 11001] getaddrinfo failed File "urllib3\connection.py", line 169, in _new_conn conn = connection.create_connection( File "urllib3\util\connection.py", line 73, in create_connection for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM): File "socket.py", line 953, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): NewConnectionError: <urllib3.connection.HTTPSConnection object at 0x00000177DC7693A0>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed File "urllib3\connectionpool.py", line 699, in urlopen httplib_response = self._make_request( File "urllib3\connectionpool.py", line 382, in _make_request self._validate_conn(conn) File "urllib3\connectionpool.py", line 1010, in _validate_conn conn.connect() File "urllib3\connection.py", line 353, in connect conn = self._new_conn() File "urllib3\connection.py", line 181, in _new_conn raise NewConnectionError( MaxRetryError: HTTPSConnectionPool(host='www.wordreference.com', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x00000177DC7693A0>: Failed to establish a new connection: [Errno … -
How can i make a custom user model in django without using username field?
I am working on building a project and for this, i need to create a custom user model, since the one that Django comes with isn't suitable for my situation, so whenever i use the AbstractBaseUser, I am forced to use the username field, which i really don't need in my case. how can I create a custom user model without using the username field and thank you -
Upload file from Django app to IBM Cloud Object Storage
I'm trying to connect a django app to IBM COS and having trouble. I'm capturing user video and want to save the file to IBM COS and the user info to Postgres also hosted on IBM. I'm able to connect from both the terminal and my app to IBM COS and move files around, but am having trouble getting the default storage configured properly. I'm using django-storages, trying to adapt the AWS configurations for IBM but I must be missing something. This code will save the file to IBM COS, but makes no entries in the DB. The problem may be in the configuration? Also, I am not able to manually upload a file form the django admin panel - I get a similar traceback. Thanks in advance for any help. settings.py # IBM STORAGE CONFIG IBM_API_KEY_ID = 'IBM_API_KEY_ID' IAM_SERVICE_ID = 'IAM_SERVICE_ID' ENDPOINT = 'https://s3.us-east.cloud-object-storage.appdomain.cloud' IBM_AUTH_ENDPOINT = 'https://iam.bluemix.net/oidc/token' SERVICE_INSTANCE_ID = 'SERVICE_INSTANCE_ID' IBM_STORAGE_BUCKET_NAME = 'cloud-object-storage-3u-cos-standard-77w' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' models.py class Video(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) videofilename=models.CharField(max_length=500) videofile=models.FileField(upload_to="video/", null=True, verbose_name="") def __str__(self): return str(self.videofile) views.py class upload_to_ibm_auto(LoginRequiredMixin, CreateView): model = Video context_object_name = 'Videos' form_class = VideoForm template_name = 'app_video/upload_to_ibm_auto.html' success_url … -
How can I remove the None or set the good status for a celery task?
Hello when I launch a celery task I got that for instance : [2021-09-22 22:11:26,878: INFO/ForkPoolWorker-7] Task Todos.celery.launchalert[886eb5a6-66cf-4759-a208-7245aca9882b] succeeded in 26.386354280999512s: None If the task is ok or have errors I got None and succeeded ... How can I do to either remove that either show the right logs ? Thank you very much ! -
Django Migration Modify Inherited Default
I have a model class in Django Parent with a subclass Child. Parent has a boolean field foo which defaults to True that Child inherited. I'd like to migrate my Child class so that All new Child objects have a default of False for the foo field All existing Child objects have the foo field set to False How can I achieve this in Django? -
Can I extend my Django project with FastAPI without changing the django app?
I have developed a Django e-commerce platform and then realized that I need to use FastAPI with it in order for my website to accept payments from the square payment system. I have looked through their documentation about how to do it, and they use fast API. However, I have no experience using Fast API at all. Is there a way for me to set up this fast API functionality without changing my Django project (so that it runs "together" with my Django app)? Or maybe there is another way which you would recommend me to use? -
Django static file problem. Clicking on the files downloads
sorry for my bad english. My index.html file cannot find the files in the static folder. When I view the page source, I click on the css file and I get different errors from time to time. Sometimes I get 404 error when I click on css link. Sometimes when I click on the css file, it downloads the file. Settings.py: import os from pathlib import Path DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "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', ], }, }, ] AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'tr' TIME_ZONE = 'Europe/Istanbul' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_ROOT = os.path.join(BASE_DIR, '/static/') STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' Urls.py: from django.conf import settings from django.conf.urls import static from django.contrib import admin from django.urls import path from django.urls.conf import include from django.conf.urls.static import static urlpatterns = [ path('', include("home.urls"), name="anasayfa"), … -
Django is not populating correctly an specific form using a Queryset
I have created two models Leads and Deals, and I have coded some logic such that if you click a button the Lead becomes a Deal, so what I want it is that a new form is presented to the user but that form already contains the information from the Leads model. @login_required def close_lead(request): if request.method == 'POST': deal_form = DealForm(request.POST) if deal_form.is_valid(): deal_form.save() messages.success(request, 'You have successfully updated the status from open to Close') id = request.GET.get('project_id', '') obj = Leads.objects.get(project_id=id) obj.status = "Closed" obj.save(update_fields=['status']) return HttpResponseRedirect(reverse('dashboard')) else: messages.error(request, 'Error updating your Form') else: id = request.GET.get('project_id', '') obj = get_object_or_404(Leads, project_id=id) print(obj.expected_revenue) form = NewDealForm(request.POST or None, instance=obj) return render(request, "account/close_lead.html", {'form':form}) I have done some debug and printed to the console the queryset and the information is fine, so the queryset is no the problem, the problem is that the NewForm doesn't prepopulate the new values. models.py (only 2 models shown) class Leads(models.Model): CHOICES = ( ('Illumination Studies','Illumination Studies'), ('Training','Training'), ('Survey Design','Survey Design'), ('Software License','Software License') ) STATUS = (('Open','Open'), ('Closed','Closed'), ('Canceled', 'Canceled') ) project_id = models.BigAutoField(primary_key=True) company = models.ForeignKey(Company, on_delete=models.CASCADE) agent = models.ForeignKey(Profile, on_delete=models.CASCADE, default="agent") created_at = models.DateTimeField(auto_now_add=True) point_of_contact = models.ForeignKey(Client, on_delete=models.CASCADE) expected_revenue = MoneyField(max_digits=14, … -
Django Combine Many Unrelated Models on Related Foreign Key
I have 3 models T, E, Q such that: class E(Model): name_e = CharField() class T(Model): name_t = CharField() e = ForeignKey(E) class Q(Model): name_q = CharField() e = ForeignKey(E) I also have Serializers for each: class ESerializer(ModelSerializer): class Meta: model = E fields = '__all__' class TSerializer(ModelSerializer): e = ESerializer() class Meta: model = E fields = '__all__' class QSerializer(ModelSerializer): e = ESerializer() class Meta: model = E fields = '__all__' For one E row there can be many T and Q rows. I can make a query such that t = T.objects.filter(e__id=1).all() serialized_t = TSerializer(t, many=True).data And the output of serialized_t will look something like: [ {id:7, name_t:'test_1', e:{id:1, name_e:'ename_1'}}, {id:9, name_t:'test_2', e:{id:1, name_e:'ename_1'}} ] My question is how could I combine it so that I can include Q in the query above to create an output for the T query which would also include all Q's where e_id=1 and hence it would look something like this: [ {id:7, name_t:'test_1', e:{id:1, name_e:'ename_1'}, q:[{id:4, name_q:'qname_1'}, {id:5, name_q:'qname_2'}]}, {id:9, name_t:'test_2', e:{id:1, name_e:'ename_1'}, q:[{id:4, name_q:'qname_1'}, {id:5, name_q:'qname_2'}]} ] I don't mind if this can be done in-query itself, or if it involves some appending to the SerializedT object, as long as … -
How do I use queryset.upgrade in a Django Admin action?
I have a Django Admin action which updates values (including foreignkeys) in a model. The code is: def staff_reset(self, request, queryset): updated=queryset.update(regstatus='registered', medicalform__medform_status='required', staffmonitoringform__monitoring_status = 'required', staffreleaseform__release_status ='required', staffethics__ethics_status = 'required', staffethics__i_agree=False) self.message_user(request, ngettext( '%d staff registration was successfully reset.', '%d staff registrations were successfully reset.', updated, ) % updated, messages.SUCCESS) staff_reset.short_description="Reset Staff Registrations" But I get an error message saying "Order has no field named 'medicalform__medform_status'". Any ideas on if I can use the queryset.update() with foreignkeys? Thanks in advance. -
How read files with load_workbook in heroku
My application is reading a file from my computer and this works fine in localhost mode. But in heroku I need to find and read this file, but it is not working: def carregaGeneroEspecie(self): wb = load_workbook(filename='/pages/setup/2021-02-12 All-DungBeetle-species_FVZ-Collection.xlsx') sheet2 = wb['Sheet1'] return sheet2 Is it possible to read xlsx files in heroku? How to find it? -
Issues with deployment on heroku from Django
I am needing help with deploying my Django app to heroku. My Django project works locally, but when I deploy to Heroku, the app crashes and cant load the index/home page. I'm not quite sure what the issue is with the GET request. here are the heroku logs --tail: 2021-09-22T20:25:16.636085+00:00 heroku[web.1]: Starting process with command `gunicorn solarsystem.wsgi` 2021-09-22T20:25:17.678063+00:00 app[web.1]: [2021-09-22 20:25:17 +0000] [4] [INFO] Starting gunicorn 20.1.0 2021-09-22T20:25:17.678545+00:00 app[web.1]: [2021-09-22 20:25:17 +0000] [4] [INFO] Listening at: http://0.0.0.0:34748 (4) 2021-09-22T20:25:17.678598+00:00 app[web.1]: [2021-09-22 20:25:17 +0000] [4] [INFO] Using worker: sync 2021-09-22T20:25:17.681856+00:00 app[web.1]: [2021-09-22 20:25:17 +0000] [7] [INFO] Booting worker with pid: 7 2021-09-22T20:25:17.685446+00:00 app[web.1]: [2021-09-22 20:25:17 +0000] [7] [ERROR] Exception in worker process 2021-09-22T20:25:17.685447+00:00 app[web.1]: Traceback (most recent call last): 2021-09-22T20:25:17.685455+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker 2021-09-22T20:25:17.685455+00:00 app[web.1]: worker.init_process() 2021-09-22T20:25:17.685456+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 134, in init_process 2021-09-22T20:25:17.685456+00:00 app[web.1]: self.load_wsgi() 2021-09-22T20:25:17.685456+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi 2021-09-22T20:25:17.685457+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2021-09-22T20:25:17.685457+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi 2021-09-22T20:25:17.685458+00:00 app[web.1]: self.callable = self.load() 2021-09-22T20:25:17.685458+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 58, in load 2021-09-22T20:25:17.685458+00:00 app[web.1]: return self.load_wsgiapp() 2021-09-22T20:25:17.685458+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp 2021-09-22T20:25:17.685459+00:00 app[web.1]: return util.import_app(self.app_uri) 2021-09-22T20:25:17.685459+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/util.py", line 359, in import_app 2021-09-22T20:25:17.685460+00:00 app[web.1]: … -
How to redirect to object returned by Ajax autocomplete in django?
I'm fetching objects from the database by using Ajax autocomplete on a common search input field. I would now like to make the rendered results clickable and redirect to the page of the object. // jQuery autocomplete search $(function () { $('#header-search-bar').autocomplete({ // data to be passed from backend source: '/autocomplete/', // length of search string minLength: 3, // redirect to pollers select: function(event, ui) { location.href="poller/" + ui.item.poller_id; } }) }) // Django view / backend query to database def autocomplete(request): if 'term' in request.GET: qs = Poller.objects.filter(poller_text__icontains=request.GET.get('term')) pollers = list() for poller in qs: pollers.append(poller.poller) return JsonResponse(pollers, safe=False) else: pass // Model class Poller(models.Model): poller_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) poller_text =models.CharField(min_length=250) // Redirect url to single Poller path('poller/<uuid:poller_id>/', render_single_poller, name='single_poller'), So the desired url for a redirect would be poller/poller_id/ The above jQuery approach renders the poller_text of each object but doesn't redirect to it. So how can I additionally "build" the required url and redirect to it as I don't know how to append more to the list than poller_text. Right now it returns http://127.0.0.1:8000/pollboard/poller/undefined -
How do I use a related name field in a Q object
I am building a search screen, and one of the query choices is to search by "string". So I am trying to get all instances of a string in a primary model AND any instances of the same string in a related model - but - I only want the related instances that exist with the string. For example - one could search for the word "Tiger" in the Program title field, library field, remarks field and also in the Segment Author field, title field, library field etc... So that being said - here's the models. class Program(models.Model): air_date = models.DateField(default="0000/00/00") air_time = models.TimeField(default="00:00:00") service = models.CharField(max_length=10) title = models.CharField(max_length=190) library = models.CharField(max_length=190, blank=True) remarks = models.TextField(null=True,blank=True) class Segment(models.Model): program = models.ForeignKey(Program, on_delete=models.CASCADE, related_name='segments', ) title = models.CharField(max_length=190, blank=True) author = models.CharField(max_length=64,null=True,blank=True) voice = models.CharField(max_length=64,null=True,blank=True) library = models.CharField(max_length=190) summary = models.TextField() My Q object for Program looks like this... q_words = [] q_words = query.split() query_prog_title_array = reduce(or_,[Q(title__icontains=w) for w in q_words]) query_prog_library_array = reduce(or_,[Q(library__icontains=w) for w in q_words]) query_prog_remarks_array = reduce(or_,[Q(remarks__icontains=w) for w in q_words]) program_results = Program.objects.filter( query_prog_title_array | query_prog_library_array | query_prog_remarks_array).order_by('id').distinct() My Q object for Segment looks like this... q_words = [] q_words = query.split() query_title_array = … -
Django Rest Framework Image/File upload
I'm aiming at having images uploaded via and endpoint unto which i've looked at most of the previous questions and answers but i haven't suceeded on having this work. Besides the django rest framework I'm using drf-flex-fields and versatileimagefield packages Below is my code: Post model; class Post(models.Model) content = models.TextField() image = models.ManyToManyField(PostImage, related_name='posts_images') updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) author = models.ForeignKey( "profiles.Profile", on_delete=models.CASCADE, null=True, related_name='posts') -
React Pagination Factory and Django API Pagination
My goal is to paginate the results for react-bootstrap-table2's pagination with a Django api. My problem is that the table is taking data from a results array from the api endpoint. Thus leading me to set the state with the data within the results. The api currently limits an offset of 100 per request. Instead I would need the count, next endpoint, and prev if applicable. How can I get the next bit of data from the offset? Another issue related, when I query without adding .results on setMealDashboard(data) I get undefined and it's expecting an array, despite adding results.id to the columns. How can I get around this so it's all in my mealDashboardData state? Pagination Const: const pagination = paginationFactory({ sizePerPage: 50, showTotal: true, }); My data: count: 600 next: "http://localhost:8000/api/meals/?limit=100&offset=100" previous: null results: [..... const [mealDashboardData, setMealDashboard] = useState([]); useEffect(() => { const getMealDashboard = async () => { try { const { data } = await fetchContext.authAxios.get( `/api/meals/` ); setMealDashboard(data.results); console.log(data); } catch (err) { console.log(err); } }; getMealDashboard(); }, [fetchContext]); My component: <ToolkitProvider bootstrap4 keyField="id" data={mealDashboardData} columns={columns} search > {(props) => ( <div> <div className="search float-right"> <SearchBar {...props.searchProps} /> <button type="button" className="btn" onClick={() => props.searchProps.onSearch('')} … -
how to run django project using docker
I am trying to create a docker container to run my django project. Following different other questions, I managed to obtain a successful build with docker. I have created a Dockerfile, docker-compose and I have created a local postgres database. and if I run the project from the entrypoint (chain of makemigration, migrate and runserver) the service can be reached. the problem is when I dockerize the project. my docker-compose.yml file is version: "3.9" services: db: restart: always image: postgres:12.0-alpine volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=signalcrossingrestapi - POSTGRES_USER=$POSTGRES_LOCAL_USER - POSTGRES_PASSWORD=$POSTGRES_LOCAL_PASSWORD env_file: - ./.env web: restart: always build: dockerfile: Dockerfile context: . volumes: - .:/code ports: - "8000:8000" depends_on: - db env_file: .env command: ./run.sh volumes: postgres_data: driver: local and the dockerfile is FROM python:3.8-slim # set up the psycopg2 RUN apt-get update && apt-get install -y libpq-dev gcc postgresql-client ENV PYTHONUNBUFFERED=1 ENV VIRTUAL_ENV=/opt/venv RUN python3 -m venv $VIRTUAL_ENV ENV PATH="$VIRTUAL_ENV/bin:$PATH" WORKDIR /code ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /code/ RUN pip install psycopg2==2.8.3 RUN pip install --upgrade pip && pip install --no-cache-dir -r requirements.txt RUN apt-get autoremove -y gcc EXPOSE 8000 when I execute docker-compose up --build it is successful but when I open localhost:8000 I cannot reach … -
Using Git on DigitalOcean server: error: The following untracked working tree files would be overwritten by merge
I am using Django for my site on DigitalOcean. So, I had to delete the migration files for one of my apps (accounts) and run makemigrations again. I don't really recall when or why, but it has caused this error when I pull from origin: $ git pull origin master From https://github.com/... ... error: The following untracked working tree files would be overwritten by merge: accounts/migrations/0001_initial.py Please move or remove them before you merge. Aborting Locally, my accounts app has only one migration: accounts > migrations __init__.py 0001_initial.py When I run git status on the server, I get a lot of untracked files, and I can see two migrations related to my accounts app (even though locally I only have one migration file in the accounts/migrations) as well as other untracked files (not related to accounts app): On branch master Untracked files: (use "git add <file>..." to include in what will be committed) accounts/migrations/0001_initial.py accounts/migrations/0002_alter_user_id.py ... Given that I don't want to mess with the production database, I don't wish you to change the migration files on the server to replicate the local migration files unless this does not cause any problem for my server. So, how should I resolve … -
Django form doesn't save value in multiple choice fields
I'm using Django's ModelForm and for no reason my form doesn't save the value of multiple choice fields. This is my models.py: class CaptureVersion(models.Model): id_capture = models.AutoField(primary_key=True) name = models.CharField(unique=True, max_length=50, verbose_name="Nom Disseny") int_reference_number = models.CharField(max_length=15, unique=True, blank=True, null=True, verbose_name='IRN') capture_version_id_provider = models.ForeignKey(Provider, on_delete=models.CASCADE, db_column='id_provider', verbose_name='Proveïdor') associated_register = models.CharField(max_length=150, blank=True, null=True, verbose_name='Registre associat') start_date = models.DateField(blank=True, null=True, verbose_name='Data Alta') end_date = models.DateField(blank=True, null=True, verbose_name='Data Baixa') target_size = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True, verbose_name='Regions diana (Mb)') probe_size = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True, verbose_name='Sondes (Mb)') sections = models.ManyToManyField(Section, blank=True, verbose_name="Secció") responsibles = models.ManyToManyField(Responsible, blank=True, verbose_name="Responsable/s") class Meta: ordering = ['start_date'] db_table = 'capture_version' And my forms.py: class FormulariCaptura(ModelForm): class Meta: model = CaptureVersion fields = ("name", "int_reference_number", "capture_version_id_provider", "associated_register", "start_date", "end_date", "target_size", "probe_size", "sections", "responsibles",) The problem are the fields sections and responsibles which are foreign keys. When I select one of the values of the dropdown list in the form, there's no problem and the entry is saved with no apparent errors but the value in the table for that field is -. But if I do it in the admin, it works or if I edit the entry with UpdateView. This worked yesterday and I didn't change anything... My views.py: def … -
Django - link to url from different apps redirecting to the same links
I have three apps in the project which have different templates with different URLs but one I go the someone app template page then the links on this page are showing to other app URL whereas I have different apps with different URLs name When I changed the name of templates files of every app then working fine. Please give me a solution what is the problem getting with the same name file in a different app. Thanks Admin App urlpatterns = [ path('login', views.login, name='admin_login'), path('register', views.register, name='admin_register'), path('logout', views.logout, name='admin_logout'), path('dashboard', views.dashboard, name='admin_dashboard') ] templates ----pages ------login.html ------register.html Customer App urlpatterns = [ path('login', views.login, name='customer_login'), path('register', views.register, name='customer_register'), path('logout', views.logout, name='customer_logout'), path('dashboard', views.dashboard, name='customer_dashboard') ] templates ----pages ------login.html ------register.html When I changed to templates ----pages ------customer_login.html ------customer_register.html Then working but I can not find an issue why is giving this type of error whereas I have a different app with different vies, templates, URLs, and pathname where I'm redirecting. Thanks in advance -
Passing data from javascript to python view in Django using ajax and saving it to database
I have created review section where user enter their reviews and then it gets saved to database. My problem here is ajax section, what i want is that on click of submit button the data which is stored in JavaScript variable get passed to python view in Django using ajax and get updated to MySQl. Html code of review <section> <div class="modal hidden"> <button class="exit">&times;</button> <div class="reviewer-detail"> <img class="review_img" src="{% static 'Images/Farmer3.jpg' %}"> <p class="review_name">Name:<span class="rn">Abhiraj Yadav</span></p> </div> <textarea type="text" placeholder="Enetr your review..." class="review_input" ></textarea> <button class="review_submit">Submit</button> </div> </section> <script src="http://code.jquery.com/jquery-1.10.2.js"></script> <script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> JavaScript side code const submitReview=document.querySelector(".review_submit") submitReview.addEventListener("click",function(e){ e.preventDefault() const input=inputReview.value; console.log(input) $.ajax({ url:'http://localhost:8000/FarmaHome/review', type:"GET", headers:{ 'X-CSRF-TOKEN':$('meta[name="csrf-token"]').attr('content') }, data:{'userInput':input}, success:function(){ alert(`Thankyou ${user_data.name}`); } }) }); url section from django.urls import path, include from .import views urlpatterns = [ path('', views.home), path('your-orders/', views.customerOrder), path('',include('django.contrib.auth.urls')), path('userlogin/', views.userLogin), path('register/', views.register), path('pesticide/',views.pesticide), path('fertilizers/',views.fertilizers), path('review/',views.review), ] Python view def review(request): mydb = mysql.connector.connect(host="localhost", user="root", password="windows10", database="farmaproduct") curr = mydb.cursor() sql = "select * from efarma_customer" curr.execute(sql) input = request.GET.get("userInput") try: curr.execute(f"update efarma_customer set review={input} where link_id={user_id}"); except: mydb.rollback() mydb.close() return render(request, 'efarma/home.html', {'input': input}) Any help would be appreciated thanks in advance.