Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
My ModelForm isn't getting auto-populated
In the update template my form isnt getting prepopulated however the functionality of updating is working fine. the form stays empty when i am trying to parse an instance of a specific ID My view.py : def update_component(request, pk): component = Component.objects.all() component_id = Component.objects.get(id=pk) form = ComponentModelForm(instance=component_id) if request.method == 'POST': form = ComponentModelForm(request.POST, instance=component_id) if form.is_valid(): form.save() return HttpResponseRedirect(request.path_info) context = { 'components': component, 'form': ComponentModelForm(), 'component_id':component_id, } return render(request, 'update_component.html', context) The form in template : <div> {% load widget_tweaks %} <form class="component-form-flex" method='POST' action=''> {% csrf_token %} <div style="width:50%;" > <br> <span class="component-label-text">Name</span> {% render_field form.name class="component-form" %} <span class="component-label-text">Manufacturer</span> {% render_field form.manufacturer class="component-form" %} <span class="component-label-text">Model</span> {% render_field form.model class="component-form" %} <span class="component-label-text">Serial Number</span> {% render_field form.serial_number class="component-form" %} <span class="component-label-text">Price</span> {% render_field form.price class="component-form" %} <span class="component-label-text">Note</span> {% render_field form.note class="component-form" %} {% render_field form.parent class="component-form" %} <input type="submit" class="form-submit-button" value='Update Component' /> </div> <div> <img class="maintenance-nav-list-img" src="{{ component_id.image.url }}" /> {% render_field form.image %} </div> </form> </div> urls.py : from django.urls import path from . import views appname = 'maintenance' urlpatterns = [ path('', views.index , name='maintenance'), path('<int:pk>/update/', views.update_component , name='update_component'), ] -
mach-o, but wrong architecture - psycopg2
I've set up my PostgreSQL database and running with Django, but I get the error mach-o, but wrong architecture. I'm on M1 Macbook Air. Info Platform: Django Database: PostgreSQL Virtual environement: conda settings.py database configuration DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'pfcbookclub', 'USER': 'admin', 'PASSWORD': 'g&zy8Je!u', 'HOST': '127.0.0.1', 'PORT': '5432', } } Description This error occurs when I try to run python3 manage.py runserver. Error and stack trace Watching for file changes with StatReloader Exception in thread Thread-1: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 954, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception raise _exception[0](_exception[1]).with_traceback(_exception[2]) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in … -
Django JSONField Constraint
I have a model that represents an email, which was sent via my Provider X. Im getting a callback from X with data, that I would like to save in the field called additional_recipients. Because of some mailing list only allowing 5 max additional recipients, i need to limit the jsonfield to only contain max 5 emails per row class EmailCallback(models.Model): additional_recipients = models.JSONField(default=list) Is it possible, to limit the JsonField so it it only holds max 5 values? [{"value": "email1"}, {"value": "email2"}, {"value": "email3"}, {"value": "email4"}] I know i can do class Meta: constraints = [ CheckConstraint(...) ] But i was wondering if thats even doable? Using Django 3.2.8 :) -
Django testinng of models.py foreign key error
I am testing the testing the models.py file which contain two class one is Farm and another one is Batch and Batch has a foreign key related to farm while testing the batch I have tested all the other columns but not sure how should I test the foreign key column of batch class models.py file lopoks like class Farm(models.Model): farmer_id = models.PositiveIntegerField() # User for which farm is created irrigation_type = models.CharField(max_length=50, choices=config.IRRIGATION_TYPE_CHOICE) soil_test_report = models.CharField(max_length=512, null=True, blank=True) water_test_report = models.CharField(max_length=512, null=True, blank=True) farm_type = models.CharField(max_length=50, choices=config.FARM_TYPE_CHOICE) franchise_type = models.CharField(max_length=50, choices=config.FRANCHISE_TYPE_CHOICE) total_acerage = models.FloatField(help_text="In Acres", null=True, blank=True, validators=[MaxValueValidator(1000000), MinValueValidator(0)]) farm_status = models.CharField(max_length=50, default="pipeline", choices=config.FARM_STATUS_CHOICE) assignee_id = models.PositiveIntegerField(null=True, blank=True) # Af team user to whom farm is assigned. previous_crop_ids = ListTextField(base_field=models.IntegerField(), null=True, blank=True, size=None) sr_assignee_id = models.PositiveIntegerField(null=True, blank=True) lgd_state_id = models.PositiveIntegerField(null=True, blank=True) district_code = models.PositiveIntegerField(null=True, blank=True) sub_district_code = models.PositiveIntegerField(null=True, blank=True) village_code = models.PositiveIntegerField(null=True, blank=True) farm_network_code = models.CharField(max_length=12, null=True, blank=True) farm_health = models.IntegerField(validators=[MaxValueValidator(100), MinValueValidator(0.1)], help_text="In Percentage", null=True, blank=True) class Batch(models.Model): commodity_id = models.PositiveIntegerField(null=True, blank=True) commodity_variety_id = models.PositiveIntegerField(null=True, blank=True) farm_id = models.ForeignKey(Farm, on_delete=models.CASCADE, related_name="batches", null=True, blank=True, db_column='farm_id') start_date = models.DateTimeField(null=True, blank=True) acerage = models.FloatField(verbose_name='Batch Acerage', help_text="In Acres;To change this value go to farms>crop" , validators=[MaxValueValidator(1000000), MinValueValidator(0.01)]) batch_health = models.IntegerField(validators=[MaxValueValidator(100), MinValueValidator(0)], help_text="In Percentage", … -
django - How to auto-populate existing data in django form while updating
I want to auto populate my update form in django with the existing data, but instance=request.user and instance=request.user.profile seems not to be auto populating the form views.py def UserProfile(request, username): # user_profiles = Profile.objects.all() user = get_object_or_404(User, username=username) profile = Profile.objects.get(user=user) url_name = resolve(request.path).url_name context = { 'profile':profile, 'url_name':url_name, } return render(request, 'userauths/profile.html', context) @login_required def profile_update(request): info = Announcements.objects.filter(active=True) categories = Category.objects.all() user = request.user profile = get_object_or_404(Profile, user=user) if request.method == "POST": u_form = UserUpdateForm(request.POST, instance=request) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile.user) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Acount Updated Successfully!') return redirect('profile', profile.user.username) else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form, } return render(request, 'userauths/profile_update.html', context) -
daemonizing celery worker and beat (environment variables problem or settings.py problem?)
I've been trying to daemonize celery and celerybeat using init scripts and systemd. The problem is that celery's tasks can't access rabbitmq and django database(postgresql in my case) because i moved my username and passwords to ~/.bashrc. for solving this problem celery documentation suggests: The daemonization script is configured by the file /etc/default/celeryd. This is a shell (sh) script where you can add environment variables like the configuration options below. To add real environment variables affecting the worker you must also export them (e.g., export DISPLAY=":0") Daemonization docs this gave me a hint to set variables in /etc/default/celeryd like this: export DJANGO_SETTINGS_MODULE="project.settings" export CELERY_BROKER_URL="ampq..." export DATABASE_USER="username" export DATABASE_PASSWORD="password" export REDIS_PASS="password" so after this, celery worker connects to rabbitmq virtualhost sometimes! most of the time it connects to rabbitmq as default guest user. before this it would always connect as guest user. when it connects as my user, worker and beat perform tasks without any problem. my tasks get and update objects from database and cache(redis). they work fine when i run them manually. I've read logs and it's always postgresql auth error by beat or the fact that worker is connected to rabbitmq as guest user. What is the solution … -
How to develop in django external python script management system?
Pseudocode: Uploud file xml or csv. I have many external python script which i want to run in queue (for example one script check if XML contains something...) I want decide which task must be switch off via admin panel. I need a report whats is the result of function. Requirements: Files size up to 150 MB size Unlimited amount of script Running scripts in sequence and saving the result Easy disabling scripts in admin panel How to build a concept of such an application in django? the scripts sequence process will be carried out in sequence. One file, then another - in a queue. The results will be available after some time. -
How can I clear the local storage when clicking the 'Login as user' button on django admin?
I want to delete the local storage of my browser when I click the button login as user of django admin page (see image). Is there a way to extend the code of that button? I have not found a way to override it. We are using django 1.11 (I know, it's old, but we cannot change that right now). -
Custom view with email parameter in django changing the url and showing http status code 301,302
myapp model: class GroupMailIds(models.Model): local_part = models.CharField( max_length=100, verbose_name='local part', help_text=hlocal_part ) address = models.EmailField(unique=True) domain = models.ForeignKey(Domain,on_delete=models.CASCADE, related_name='domains') def __str__(self): return self.address In myapp urls.py: from . import views from django.urls import path, include from django.http import * urlpatterns = [ path('', views.index, name='index'), path('groupmailids/<str:email>/details', views.get_groupmailid_details, name='get_groupmailid_details'),] myapp views.py: def get_groupmailid_details(request, email): data = {} if request.method == 'POST': return redirect('home') else: try: groupmailid_obj = GroupMailIds.objects.filter(address=email)[0] print(groupmailid_obj, '--------groupmailid_objjjjjjjj') except Exception as e: groupmailid_obj = None if groupmailid_obj: data.update( {'groupmailid_id':groupmailid_obj.id, 'address':groupmailid_obj.address, }) print(data) return JsonResponse(data) But when in browser I use the url: localhost:8000/admin/mailmanager/groupmailids/newgroup@saintmartincanada.com/details id displays the main menu with message: Group email id with ID “newgroup@saintmartincanada.com/details” doesn’t exist. Perhaps it was deleted? The above code worked for sometime very well, but suddenly stopped working, in the console can see trace log messages like: "GET /admin/mailmanager/groupmailids/newgroup@saintmartincanada.com/details HTTP/1.1" 301 0 [12/Jan/2022 18:18:22] "GET /admin/mailmanager/groupmailids/newgroup@saintmartincanada.com/details/ HTTP/1.1" 302 0 [12/Jan/2022 18:18:23] "GET /admin/mailmanager/groupmailids/newgroup@saintmartincanada.com/details/change/ HTTP/1.1" 30 Unable to fix this issue. Why is it appending '/change' to the url? and returning to the admin page in GUI? It is showing http status code 301, 302 in the logs ? I am using django 3.2 , python 3.7 Please can you suggest the correct code? -
Creating a chart based on the last id introduced in the database
this is going to be a big question to read, so sorry for that, but I can't get my head around it. I want to create a chart, but only with values for the last added id in the database, for that i have the following model: class Device (models.Model): patientId = models.IntegerField(unique=True) deviceId = models.CharField(unique=True,max_length=100) hour = models.DateTimeField() type = models.IntegerField() glucoseValue = models.IntegerField() I have an upload button that accepts an txt, it converts it into a excel file and then it add every row in the database, here is the UI: The UI of the application For sending the data, I'm using the following code in views.py: def html(request, filename): #Data for the graph id = list(Device.objects.values_list('patientId', flat=True).distinct()) labels = list(Device.objects.values_list('hour', flat=True)) glucose_data = list(Device.objects.values_list('glucoseValue', flat=True)) data = glucose_data test123 = select_formatted_date(labels) print(test123) #f = DateRangeForm(request.POST) context = {"filename": filename, "collapse": "", "patientId": id, "dataSelection": test123, "labels": json.dumps(labels, default=str), "data": json.dumps(data), #"form": f } For accepting the data, i have the following structure in index.html: var ctx = document.getElementById("weeklyChart"); var hourly = document.getElementById("dailyChart"); var myLineChart = new Chart(ctx, { type: 'line', data: { labels: {{ labels|safe}}, datasets: [{ label: "Value", lineTension: 0.3, backgroundColor: "rgba(78, 115, 223, 0.05)", … -
How to change automatic datetime to a date is given in Json Django?
I am new to Django. I am trying to save the datetime that is given in the json structure in a start_date field which is auto_now. But it does not work it keeps saving the cuurent date in the database not the date that is given in Json: ( "available_from_date": "2022-07-08 00:00:00.000000"). How can I change that to the date given in json. In my model.py: start_date = models.DateTimeField(auto_now=True) In my views.py: room_status = RoomStatus( room =room_obj, status=5, date_start=room["available_from_date"] ) room_status.save() In json: "room": [ { "available_from_date": "2022-07-08 00:00:00.000000" } ] -
Saving multipart image coming from android to Django ImageField
I get this JSON format after sending an image in MultipartBody.Part format from Android app to Django server, Dose anyone know how to save this to ImageField in Django? {'answer_image_file': {'headers': {'namesAndValues': ['Content-Disposition', 'form-data; name="answer_image"; filename="signature-question.png"']}}, 'question_id': '9974ac18-2efd-4220-bf4b-523bdd4981af'} in Android I did @POST(SUBMIT_FORM) suspend fun submitFormBodyAPI( @Header("Authorization") token: String, @Body questionAnswer: QuestionAnswer, ): Response<FormResponse> where QuestionAnswer looks like this: data class QuestionAnswer( val question_id: String, val answer_image_file: MultipartBody.Part? = null, ) NOTE: I need to send it like that because it will solve my problem posted here with all details and code: Android Retrofit upload images and text in the same request -
Make celery use custom django middleware for logs
I'm using a custom django middleware to handle logs in my app but I dont really know how to read them from celery (asynchronous calls). Besides celery appears to ignore Django middleware so basically how can I achieve that celery goes through my custom django middleware? Thanks in advance -
Installing a package in docker
I am using docker in django project, and installed packages which are in req.txt. During project I needed to install a package and did it using docker-compose exec web pip install 'package' and docker-compose up -d --build, it installed in docker but I cannot use it in my project that not installed in project. Question: How to install package in docker? Is it possible to write installed packages to req.txt using docker? Dockerfile: FROM python:3.8 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ docker-compose.yml: version: '3.9' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db db: image: postgres:11 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - "POSTGRES_HOST_AUTH_METHOD=trust" volumes: postgres_data: -
Populating data in django admin for a many to many field based on foreign key value selected
I have a model : class AddComments(models.Model): id = models.AutoField(db_column='Id', primary_key=True, db_index=True) country= models.ForeignKey(Countries,on_delete=models.DO_NOTHING,db_column='CountryId') university=models.ManyToManyField(Universities,db_column='UniversityId',verbose_name='University') intake = models.CharField(db_column='Intake',blank=True, null=True, max_length=20, verbose_name='Intake') year=models.CharField(max_length=5,blank=True,null=True) application_status=models.ForeignKey(Applicationstages,on_delete=models.DO_NOTHING, db_column='ApplicationStageId',verbose_name='Application Status') comments=RichTextField() added_on=models.DateTimeField(auto_now_add=True) processed_on=models.DateTimeField(blank=True,null=True) processed_status=models.BooleanField(default=False) requested_by = currentuser(db_column='RequestedBy', blank=True, null=True,related_name='streamcomments_requested_user') class Meta: db_table = 'AddComments' def __str__(self): return str(self.application_status) def __unicode__(self): return str(self.application_status) in admin I want to populate the values of university based on the country selected and don't want to load all the universities data. I have checked django-smart-selects but not able to get this working with smart-selects. Any way to meet the requirement? -
mach-o, but wrong architecture in psycopg2
I've set up my PostgreSQL database and running with Django, but I get the error mach-o, but wrong architecture. I'm on M1 Macbook Air. Error and stack trace Watching for file changes with StatReloader Exception in thread Thread-1: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 954, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception raise _exception[0](_exception[1]).with_traceback(_exception[2]) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/contrib/postgres/apps.py", line 1, in <module> from psycopg2.extras import ( File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/psycopg2/__init__.py", line 51, in <module> from psycopg2._psycopg import ( # noqa ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/psycopg2/_psycopg.cpython-39-darwin.so, 2): no suitable image found. Did find: /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/psycopg2/_psycopg.cpython-39-darwin.so: mach-o, but … -
How do I calculate percentages from two tables in Django
Im pretty new to the Django Framework and I am stuck at calculating a percentage. Heres the problem: I have two tables SocialCase and Donation: class SocialCase(models.Model): title = models.CharField(max_length=200) profile = models.ForeignKey(Profile, on_delete=models.CASCADE) organizer = models.TextField(max_length=200, null=True, blank=False) description = models.TextField(null=True, blank=False) created = models.DateTimeField(auto_now_add=True) profile_image = models.ImageField(upload_to='static/images/') case_tags = models.ManyToManyField('events.Tag') target_donation = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True) class Donation(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) social_case = models.ForeignKey(SocialCase, on_delete=models.CASCADE) raised = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True) I want to use a @property method to calculate the percentage between raised and target_donation The target_donation field represents the total money needed for this social case. The target_donation will be set when the Social Case is created. The raised field represents the amount of money that has been currently raised. The raised field will be a dynamic value that will increment with each donation I want to calculate the percentage on the SocialCase model. How do I bring the raised column from Donations model in order to calculate the percentage of each Social Case and output it in the HTML template? Thank you verry much, and and sorry if this a simple question, Im still a newbie and couldnt find anything in the … -
Geodjango model combined with non geo model
I am a django beginner and trying to programm a simple geo application. My setup: django/geodjango + leaflet. Everything works fine and geo objects (GeoObject) are displayed. But now I want to add aditional properties ("status") from another model and display them also via leaflet - but I´m stuck. my models.py: class GeoObject(models.Model): name = models.CharField(verbose_name="name", max_length=20) location = models.PointField(srid=4326) class Status(models.Model): status = models.OneToOneField(GeoObject, on_delete=models.CASCADE, primary_key=True, default=0, unique=True) my views.py: def GeoMapView(request): #view to display leaflet map with geo objects q=Sensor.objects.all() context = {'q':q} return render(request, 'xitylytix_sensors/sensor_map.html', context) def GeoData(request): #sending geo data q=GeoObject.objects.all() geo_data = serialize('geojson', q) return HttpResponse(geo_data, content_type='json') my urls.py urlpatterns = [ path('geomap/', views.GeoMapView, name='geo_map'), #display via template/leaflet map path('geodata/', views.GeoData, name='geo_data'), #sending geo data ] json data: {"type": "FeatureCollection", "crs": {"type": "name", "properties": {"name": "EPSG:4326"}}, "features": [{"type": "Feature", "properties": {"name": "001", "pk": "1"}, "geometry": {"type": "Point", "coordinates": [8.849315642079313, 50.07892796957105]}}, ... I tried with one to one relation (see model), but "status" in the json file is missing in "properties". Does anyone have an idea? -
I have successfully installed django debug toolbar in my django project. Display error (ModuleNotFoundError: No module named 'debug_toolbarstore)
I have successfully installed django debug toolbar in my django project. initially server in run but currently it display this error I just run my server on cmd and its shows this error. (storefront) C:\Users\Tayyab\Desktop\storefront>python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Tayyab\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Users\Tayyab\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "C:\Users\Tayyab\.virtualenvs\storefront-K3Kf9O1H\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Tayyab\.virtualenvs\storefront-K3Kf9O1H\lib\site-packages\django\core\management\commands\runserver.py", line 115, in inner_run autoreload.raise_last_exception() File "C:\Users\Tayyab\.virtualenvs\storefront-K3Kf9O1H\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\Tayyab\.virtualenvs\storefront-K3Kf9O1H\lib\site-packages\django\core\management\__init__.py", line 381, in execute autoreload.check_errors(django.setup)() File "C:\Users\Tayyab\.virtualenvs\storefront-K3Kf9O1H\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Tayyab\.virtualenvs\storefront-K3Kf9O1H\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Tayyab\.virtualenvs\storefront-K3Kf9O1H\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\Tayyab\.virtualenvs\storefront-K3Kf9O1H\lib\site-packages\django\apps\config.py", line 223, in create import_module(entry) File "C:\Users\Tayyab\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ****ModuleNotFoundError: No module named 'debug_toolbarstore'**** -
Django ORM - filter method with some arithmetic calculation
I have this query 'SELECT * FROM products WHERE discontinued = 0 AND ((unitsinstock + unitsonorder) < reorderlevel)' which is giving me some results from DB, how can I do the same in django ORM I tried as below but this is erroring out. -
Return null instead of id or nested serialized data on json API response
So here is the code models.py class Client(models.Model): name = models.CharField(max_length=255, unique=True) company_reg_num = models.CharField(max_length=255, blank=True, null=True, unique=True) date_registerd_internal = models.DateField(auto_now_add=True) date_registerd_external = models.DateField() location = models.ManyToManyField(Location, null=True, blank=True, related_name='location') class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, blank=True, null=True) time_created = models.DateTimeField(auto_now_add=True) image = models.ImageField(default='default.png', upload_to='profile_imgs', null=True, blank=True) date_of_birth = models.DateField(blank=True, null=True) gender = models.CharField(choices=GENDER, max_length=12, default='Male') place_of_birth = models.CharField(max_length=255, blank=True, null=True) employer = models.ForeignKey(Client, on_delete=models.CASCADE, blank=True, null=True, related_name='employer') class Shift(model.Models): # --snip-- expense = models.ForeignKey(Expense, on_delete=models.CASCADE, null=True, blank=True, related_name='expense') time_added = models.DateTimeField(auto_now_add=True) employee_assigned = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True, blank=True, related_name='employee_assigned') location = models.ForeignKey(Location, on_delete=models.CASCADE, null=True, blank=True) client = models.ForeignKey(Client, on_delete=models.CASCADE, null=True, blank=True, related_name='client') And here is my serializer.py file class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' class ClientSerializer(serializers.ModelSerializer): location = LocationSerializer(read_only=True, many=True) class Meta: model = Client fields = '__all__' class ShiftSerializer(serializers.ModelSerializer): #permission_classes = [permissions.IsAuthenticatedOrReadOnly] location = LocationSerializer(read_only=True, many=False) employee_assigned = ProfileSerializer(many=False, read_only=True) client = ClientSerializer(many=False, read_only=True) class Meta: model = Shift fields = '__all__' I am using function based views for my api views and they are as follows: @api_view(['GET', 'POST', 'PATCH']) @csrf_exempt @permission_classes((IsAuthenticated,)) def shift_api(request): if request.method == 'GET': if request.user.is_superuser and request.user.is_staff: shifts = Shift.objects.all() serializer = ShiftSerializer(shifts, many=True) return Response(serializer.data, status=status.HTTP_200_OK) else: return Response({"error": … -
Django, Tailwind, and heroku collectstatic cannot find npm
I am trying to set up a small web project using Django and tailwind and deploying it on Heroku. In Heroku, I am installing the heroku/nodejs and heroku/python Buildpacks. I am going through the following guide to set it up: https://www.khanna.law/blog/deploying-django-tailwind-to-heroku When I try to deploy my application to Heroku I am getting the following error: -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "/app/.heroku/python/lib/python3.10/site-packages/tailwind/npm.py", line 23, in command subprocess.run([self.npm_bin_path] + list(args), cwd=self.cwd) File "/app/.heroku/python/lib/python3.10/subprocess.py", line 501, in run with Popen(*popenargs, **kwargs) as process: File "/app/.heroku/python/lib/python3.10/subprocess.py", line 966, in __init__ self._execute_child(args, executable, preexec_fn, close_fds, File "/app/.heroku/python/lib/python3.10/subprocess.py", line 1842, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) FileNotFoundError: [Errno 2] No such file or directory: '/usr/local/bin/npm' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.10/site-packages/tailwind/management/commands/tailwind.py", line 119, in npm_command self.npm.command(*args) File "/app/.heroku/python/lib/python3.10/site-packages/tailwind/npm.py", line 26, in command raise NPMException( tailwind.npm.NPMException: It looks like node.js and/or npm is not installed or cannot be found. Visit https://nodejs.org to download and install node.js for your system. If you have npm installed and still getting this error message, set NPM_BIN_PATH variable in settings.py to match path of NPM executable in your system. Example: NPM_BIN_PATH = "/usr/local/bin/npm" During … -
How to solve 'POST 401 Ajax Error' in the console of a deployed django website
I keep on getting an error like below in the chrome console whenever I click my "Place Order" button in my website. I have struggled with this for hours. Here is my error: POST https://{{mywebsitedomain}}/order/create_ajax/ 401 jquery-3.5.1.min.js:2 I have no idea why this error suddenly shows up after I uploaded my website on a hosting provider online. This is because I did not get this error when I was in dev mode on my pc. Here is my template: {% block script %} <script src="https://code.jquery.com/jquery-3.5.1.min.js" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script type="text/javascript"> csrf_token = '{{csrf_token}}'; order_create_url = '{% url "orders:order_create_ajax" %}'; order_checkout_url = '{% url "orders:order_checkout" %}'; order_validation_url = '{% url "orders:order_validation" %}'; order_complete_url = '{% url "orders:order_complete" %}'; </script> <script src="https://cdn.iamport.kr/js/iamport.payment-1.1.8.js" type="text/javascript"></script> {% load static %} <script src="{% static 'js/checkout.js' %}" type="text/javascript"></script> {% endblock %} {% block content %} <section class="max-w-xl mx-auto pt-10 text-gray-600 body-font"> <div class="container mx-auto flex flex-wrap"> <div class="w-full flex justify-between items-center border-b border-gray-500"> <div class="mb-1"> <a class="text-md text-blue-500 hover:text-blue-300" href="{% url 'lesson-options-list' current_product.class_type.pk %}">돌아가기</a> </div> </div> </div> </section> <div class="mt-5 max-w-xl mx-auto"> <div class="row"> <div class="col"> <div class="p-4"> <div class="flex rounded-lg h-full bg-gray-100 p-8 flex-col"> <div class="flex items-center mb-3"> <div class="w-8 h-8 mr-3 inline-flex items-center … -
filling the document Django python-docx
it is necessary to fill in the document template Word through the rest api. I load the template through the admin panel and assign the names of the fields whose values I want to receive through the api. I don’t know how to continue to be def post(self, request): data = request.data # берем данные из post запроса document = Documentt.objects.filter(id=data["doc_id"]) # ищем нужный пример документа open_doc = Document(document[0].location) # открываем его filename = ((str(document[0].location)).split('/')[-1]).split('.')[0] # создаем имя файла fields = DocumentField.objects.filter(id=data["doc_id"]) # получаем поля для данного документа # обрабатываем поля##### context = {} for field in fields: # получаем имя поля field_name = Field.objects.filter(name=str(field.field_id)) # добавляем строку в файл##### context= { f"{field_name}: {(data['field'][field_name])}" } open_doc.render(context) if os.path.exists(f"user_files/{str(data['customer_id'])}"): # проверяем существует ли папка с id пользов. pass else: os.mkdir(f"user_files/{str(data['customer_id'])}") # если не существует то создаем open_doc.save('user_files/' + str(data['customer_id']) + '/' + filename + '.docx') # сохраняем файл # проверяем наличие файла в бд if len(DocumentResult.objects.filter(title=filename)) == 0: cust = Customer.objects.get(id=data["customer_id"]) # получаем объект кастомера res_doc = DocumentResult.objects.create( title=filename, customer=cust, location='user_files/' + str(data['customer_id']) + '/' + filename + '.docx' ) # добавляем в бд return Response({'status': 'Success!', 'link': res_doc.location}) # возвращаем успешный ответ return Response({'status': 'Success!'}) -
Cannot deploy django app to strato hosting [closed]
Has anybody successfully deployed django app to strato (strato.de) web server? After some struggle I was able to install all dependencies as wall as npm and node. Basically I noticed that using strato with ssh is very limited. I am running gunicorn on my default wsgi file but when I try to reach my website from domain address, nothing happens. I noticed that there is apache installed on the machine but installing mod_wsgi via pip fails.