Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error occurred while reading WSGI handler: Django and React app deployment iis server
I'm trying to publish a web application on an IIS server with Django and React. backend is working but when i run browser for react i get below error. Why fronted gives wsgi error Error occurred while reading WSGI handler: Traceback (most recent call last): File "C:\python\lib\logging\config.py", line 565, in configure handler = self.configure_handler(handlers[name]) File "C:\python\lib\logging\config.py", line 746, in configure_handler result = factory(**kwargs) File "C:\python\lib\logging\__init__.py", line 1169, in __init__ StreamHandler.__init__(self, self._open()) File "C:\python\lib\logging\__init__.py", line 1201, in _open return open_func(self.baseFilename, self.mode, FileNotFoundError: [Errno 2] No such file or directory: 'C:\\ui\\logs\\app_2022_09_27.log' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\python\lib\site-packages\wfastcgi.py", line 791, in main env, handler = read_wsgi_handler(response.physical_path) File "C:\python\lib\site-packages\wfastcgi.py", line 633, in read_wsgi_handler handler = get_wsgi_handler(os.getenv("WSGI_HANDLER")) File "C:\python\lib\site-packages\wfastcgi.py", line 605, in get_wsgi_handler handler = handler() File "C:\python\lib\site-packages\django\core\wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "C:\python\lib\site-packages\django\__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "C:\python\lib\site-packages\django\utils\log.py", line 76, in configure_logging logging_config_func(logging_settings) File "C:\python\lib\logging\config.py", line 811, in dictConfig dictConfigClass(config).configure() File "C:\python\lib\logging\config.py", line 572, in configure raise ValueError('Unable to configure handler ' ValueError: Unable to configure handler 'app_file' -
Two different timestamps for TokenGenerators Django
I have probably a quick question. How can I set two different expire times for my TokenGenerator classes? class ActivationTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return (six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.is_active)) class PasswordResetTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return (six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.password)) I know that I can use PASSWORD_RESET_TIMEOUT in settings.py but it sets same expire time for both TokenGenerators. I need to make ActivationTokenGenerator unlimited and PasswordResetTokenGenerator to has f.e. expire_time=1day. -
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000
I got the following error whenever I run the project: Using the URLconf defined in storefront.urls, Django tried these URL patterns, in this order: admin/ playground/ The empty path didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. Here is my project(storefront) urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('playground/', include('playground.urls')), ] Here is playground urls.py code: from django.urls import path, include from . import views #urlConfig urlpatterns=[ path('hello/', views.say_hello) ] Here is views.py file: from django.shortcuts import render from django.http import HttpResponse # Create your views here. def say_hello(request): return HTTPResponse('Hello world') Here is my project settings: # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.staticfiles', 'playground' ] -
Overriding of data in MongoDB collection.update() django
I am using mongo DB In which I'm updating a row for multiple types with different payloads and conditions but every time I update the row it overrides the previous one for the first time the request. data is request.data: { "farm_area_count": 1, "farm_area": [ { "area_id": 1, "area_name": "Area 1", "area_acerage": 4, "area_structure_type": "polyhouse", "zone_latest_id": 0 } ] } output is { "farm_area_count": 1, "farm_area": [ { "area_id": 1, "area_name": "Area 1", "area_acerage": 4, "area_structure_type": "polyhouse", "zone_latest_id": 0 } ] } for the second time the request. data is request.data: { "farm_area_count": 1, "farm_area": [ { "area_id": 1, "zone_latest_id": 1, "zone_name":"test zone", "zone_acerage":2 } ] } the output should be { "farm_area_count": 1, "farm_area": [ { "area_id": 1, "area_name": "Area 1", "area_acerage": 4, "area_structure_type": "polyhouse", "zone_latest_id": 1, "zone_name":"test zone", "zone_acerage":2 } ] } but the output that I'm getting is { "farm_area_count": 1, "farm_area": [ { "area_id": 1, "zone_latest_id": 1, "zone_name":"test zone", "zone_acerage":2 } ] } here is the updated code collection.update_one({"_id": ObjectId(str(kwargs['pk']))}, {"$set": request.data}) -
I am trying to pass model as fixture to my test but it is giving me an error Object is not json serializable
Implement this method in a subclass such that it returns a serializable object for o, or calls the base implementation (to raise a TypeError). json.encoder.JSONEncoder object at 0x7fccf1cacbb0 TypeError: Object of type User is not JSON serializable from pydantic import BaseModel class User(BaseModel): first_name: str last_name: str username: str email: str contact: str password: str company_name: str address: str city: str country: str postal_code: str role_id: str license_id: str class config: orm_mode = True @pytest.fixture def user(): user = User( first_name="Ali", last_name="Hamza", username="alihamza", email="y@x.com", contact="+000000000000", password="1234567890", company_name="abc", address="xyz", city="XYZ", country="Sone", postal_code=333333, role_id=1, license_id=1 ) return user def test_get_empty_todos_list(user): user = json.dumps(user) response = client.post('/user/create/', json=user) print(response.json()) -
How build from source multiple services with docker-compose and create a single image?
I'm trying to create multiple containers for my Python/Django application called controller and I would like the containers to run in a single image, not two. The problem is that my file docker-compose.yml build two services from source and it generates two separated images as a result. The application is composed of 5 services: a Django project, Celery (worker, beat, flower) and Redis. How can I tell docker-compose to build the django and redis service from source and to create all services in the same image ? I've tried to change image: image: controller-redis with image: controller and it create a unique image with all services, but most of them failed to start because files aren't found : Logs output : $ docker-compose logs -f controller-celery_beat-1 | /usr/local/bin/docker-entrypoint.sh: 24: exec: /start-celerybeat: not found controller-django-1 | /usr/local/bin/docker-entrypoint.sh: 24: exec: /start: not found controller-flower-1 | /usr/local/bin/docker-entrypoint.sh: 24: exec: /start-flower: not found [...] controller-celery_worker-1 | /usr/local/bin/docker-entrypoint.sh: 24: exec: /start-celeryworker: not found Docker-compose ps $ docker-compose ps NAME COMMAND SERVICE STATUS PORTS controller-celery_beat-1 "docker-entrypoint.s…" celery_beat exited (127) controller-celery_worker-1 "docker-entrypoint.s…" celery_worker exited (127) controller-django-1 "docker-entrypoint.s…" django exited (127) controller-flower-1 "docker-entrypoint.s…" flower exited (127) controller-redis-1 "docker-entrypoint.s…" redis running 6378-6379/tcp docker-compose.yml version: '3.8' services: django: build: context: … -
displaying restaurants nearby a user location within 5 kilometers in Django
Good morning Everyone, I would like to display restaurants within 5 kilometers in using google maps api , How could I do it? I have done the latitudes and longitudes calculs with haversine. But i don't know how rendering the result in django. Thanks -
Streaming Excel File with Django StreamingHttpResponse
I have usecase where i have to generate and send the excel file having records upto 4M ,since the file can be large i want to stream the response while i am generating the file https://docs.djangoproject.com/en/2.0/howto/outputting-csv/#streaming-large-csv-files : this is exactly what i want but for excel file with records upto 4M Any help with this? -
Django/Heroku Deployment issue OperationalError at / no such table: posts_post
OperationalError at / no such table: posts_post Django Version: 4.1 Exception Type: OperationalError Exception Value: no such table: posts_post Exception Location: /app/.heroku/python/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py, line 357, in execute Raised during: posts.views.index Python Executable: /app/.heroku/python/bin/python Error during template rendering In template /app/templates/index.html, error at line 31 no such table: posts_post Code Highlighted in error is my Index.HTML File obj in object_list </section> <section class="featured-posts no-padding-top"> <div class="container"> <!-- Post--> {% for obj in object_list %} <div class="row d-flex align-items-stretch"> {% if not forloop.first and not forloop.last %} <div class="image col-lg-5"><img src="{{ obj.thumbnail.url }}" alt="..."></div> {% endif %} <div class="text col-lg-7"> <div class="text-inner d-flex align-items-center"> <div class="content"> <header class="post-header"> <div class="category">''' Traceback to views.py file /app/posts/views.py, line 51, in index( Highlighted line in error return render(request, 'index.html', context)) def index(request): featured = Post.objects.filter(featured=True) latest = Post.objects.order_by('-timestamp')[0:3] if request.method == "POST": email = request.POST["email"] new_signup = Signup() new_signup.email = email new_signup.save() context = { 'object_list': featured, 'latest': latest } return render(request, 'index.html', context) ''' I have tried solving it by removing pycache from my apps along with making migrations again however it throws same error.. Can anyone here help on this? Thanks -
Difficulties in extracting data from CSV and matching it with Product model, please advise
Hi I’m stuck with a Django Python project where I’m trying to build an application where you can upload a csv file to then extract its values to generate a sales report pdf. Products can be added via the admin console and if those items appear (at the right place for now, eg item 4 in each row gets checked on) in the csv file they get extracted and added to the report (calculating the sum, storing the date of each purchase). For completeness I will add the entire csv_upload_view function to then mention the specific parts I'm having difficulties with: def csv_upload_view(request): print('file is being uploaded') if request.method == 'POST': csv_file_name = request.FILES.get('file').name csv_file = request.FILES.get('file') obj, created = CSV.objects.get_or_create(file_name=csv_file) #result = [] if created: obj.csv_file = csv_file obj.save() with open(obj.file_name.path, 'r') as f: reader = csv.reader(f) reader.__next__() for row in reader: print(row,type(row)) data = " ".join(row) data = data.split(";") print(data, type(data)) # print(data[2]) #data = data.split(';') #data.pop() #print(data) transaction_id = data[1] product = data[2] quantity = int(data[3]) customer = data[4] date = parse_date(data[5]) print(transaction_id, product, quantity, customer, date) try: product_obj = Product.objects.get(name__iexact=product) except Product.DoesNotExist: product_obj = None return HttpResponse() The csv file is as follows: POS,Transaction id,Product,Quantity,Customer,Date 1,E100,TV,1,Test … -
I used Djoser for login registration can i use other 3rd party packages for social authentication django
I used Djoser for all basic authentications but when it comes to social authentications its little hard to implement could you please help -
How to change the widget for a computed field on a Django Admin model form
For a Django Admin model form, if you display a calculated field, is there a way to also specify the widget the form should used to display that field? I cannot seem to find any mention of this. All the examples I have found describe how to override a standard (i.e., non-calculated) field's widget. -
Reverse for 'about_us' with arguments '('',)' not found. 1 pattern(s) tried: ['about_us/(?P<pk>[0-9]+)\\Z']
I am trying to view a blog post in the user module that is posted by the another user module. Here's my model: class details(models.Model): about_us = models.TextField(max_length=255) def __str__(self): return self.title def get_absolute_url(self): return reverse('admin_home') views.py: class about_us(DetailView): model = details template_name = 'usertemplates/aboutus.html' I have added it to my designated template which is supposed to be shown as a different page. {% extends 'usertemplates/main.html' %} {% load static %} {% block content %} {{object_list.about_us}} {% endblock content %} also added path in urls.py: path('about_us/<int:pk>', userviews.about_us.as_view(), name = 'about_us') The error is given in my home template where I wanted the post as hyperlink. Reverse for 'about_us' with arguments '('',)' not found. 1 pattern(s) tried: ['about_us/(?P<pk>[0-9]+)\\Z'] error at following line: <a href="{% url 'about_us' post.pk %}" style="text-decoration:none;color:White;align-items:center;font-size:15px">About Us<span class="sr-only"> | </span></a> -
How to solve field error in django models file
I have been working on an ecommerce website, the models were previously working fine until i added a new app with a new customer model but had a different name, though it used the user model, i deleted the app since it really didn't matter. But after deleting, am trying to login, signup, and register but it keeps bringing the error.."Cannot resolve keyword 'user' into field. Choices are: admin, auth_token, customer, date_joined, email, first_name, groups, id, is_active, is_staff, is_superuser, last_login, last_name, logentry, notifications, password, user_permissions, username" at profile. models.py from django.db import models from django.contrib.auth.models import User # for the csv import csv from django.http import HttpResponse import datetime # working with the csv files class ExportCsvMixin: def export_as_csv(self, request, queryset): meta = self.model._meta field_names = [field.name for field in meta.fields] response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename={}.csv'.format(meta) writer = csv.writer(response) writer.writerow(field_names) for obj in queryset: row = writer.writerow([getattr(obj, field) for field in field_names]) return response export_as_csv.short_description = "Export Selected" class Admin(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) full_name = models.CharField(max_length=50) image = models.ImageField(upload_to="admins") mobile = models.CharField(max_length=20) def __str__(self): return self.user.username class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) full_name = models.CharField(max_length=200) address = models.CharField(max_length=200, null=True, blank=True) joined_on = models.DateTimeField(auto_now_add=True) actions = ["export_as_csv"] def … -
Access .data on nested serializer in django
I have the 3 following Models : class Vehicle(models.Model): name = models.CharField(max_length=250) type = models.CharField(max_length=250) engine = models.CharField(max_length=250) class GHGI(models.Model): year = models.IntegerField() created = models.DateField(auto_now_add=True) class VehicleConsumption(models.Model): vehicle = models.ForeignKey(Vehicle, related_name='vehicleconsumption', on_delete=models.CASCADE, null=True) ghgi = models.ForeignKey(GHGI, related_name='vehicleconsumption', on_delete=models.CASCADE) total = models.IntegerField(null=True) With the following nested serializer : class VehicleConsumptionSerializer(serializers.ModelSerializer): class Meta: model = VehicleConsumption fields = '__all__' class VehicleSerializer(serializers.ModelSerializer): consumptions = VehicleConsumptionSerializer(many=True, read_only=True) class Meta: model = Vehicle fields = '__all__' When I access the .data json from the nested serializer as following : vehicles = Vehicle.objects.filter(vehicleconsumption__ghgi_id=1) serializerv = VehicleSerializer(vehicles, many=True) print (serializerv.data) I have only the attributes from the Vehicles class : [OrderedDict([('id', 1), ('name', 'Voit1'), ('type', 'car'), ('engine', 'diesel')])] Or I also would like to include the data from the VehicleConsumption class : [OrderedDict([('id', 1), ('name', 'Voit1'), ('type', 'car'), ('engine', 'diesel'), ('consumptions', '...')])] what can I do to retrieve these data in the same object ? -
Django CPanel MEDIA_ROOT configuration
I have setup my Django project on CPanel. On my python setup page on Cpanel, I have mentioned my Application Root as "example" (where i have uploaded all files) and my Application Url as "example.com" settings.py contains MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py under my app contains urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) my models.py contains a field documentFile = models.FileField(upload_to='documents/files/completed/%Y/%m/%d') Now I can see two folders on CPANEL example (where i have uploaded all my files) example.com (I have not made any changes to it) I was able to visit example.com, and everything works absolutely fine. I was able to upload to file to 'documents/files/completed/%Y/%m/%d' When i check i can physically see that the file is created under the folder example But i am not able to fetch it back because, when i am trying to fetch the uploaded file, its actually tyring to fetch from example.com I am new to Django, CPanel.. Changes/Suggestion please -
It is impossible to add a non-nullable field 'user_ptr' to student without specifying a default. This is because the database needs
It is impossible to add a non-nullable field 'user_ptr' to student without specifying a default. This is because the database needs something to populate existing rows. Please select a fix: Provide a one-off default now (will be set on all existing rows with a null value for this column) Quit and manually define a default value in models.py. class User(models.Model): type_user = (('S', 'Student'), ('T', 'Teacher')) username = models.CharField(max_length=15, primary_key=True) password = models.CharField(max_length=10) firstname = models.CharField(max_length=50) middlename = models.CharField(max_length=50, null=True) lastname = models.CharField(max_length=50) type = models.CharField(max_length=1, choices=type_user) class Student(User): #username = models.CharField(max_length=15, primary_key=True) course = models.CharField(max_length=15, null=False) year = models.IntegerField(default=1, null=False) department = models.CharField(max_length=50, null=False) -
Order data by latest uploaded in django FBV
I have a list view where i display the uploaded records right now they are sorted by name i need to change them to sort them by created date(which is in model). @login_required def records(request, template='records.html'): FBVPermission(IsUser).check(request) user = request.user.person.is_user data = {'user':user, 'records': user.records.all()} return render(request, template, data) -
In django whats the difference between mergemigrations and squashmigrations?
When shall we use mergemigrations --meerge/mergemigrations and when to use squashmigrations can we execute these commands via pipeline insteed of each developer in team doing it manually ? -
Cannot find webdriver executable in CircleCI
I'm new to CircleCI and have a django project repo that runs some selenium tests successfully locally, but when they try to run on CircleCI, they cannot find the webdriver, even though I've referenced it in the executable_path param as well as including in the repo. In the edge driver init fixture below, I reference the executable path: # conftest.py @pytest.fixture(scope="class") def edge_driver_init(request): options = webdriver.EdgeOptions() options.add_argument("--headless") edge_driver = webdriver.Edge( executable_path='webdrivers/msedgedriver.exe', options=options ) request.cls.driver = edge_driver yield edge_driver.close() The webdriver folder containing the exectuble is in the root directory of the Django project (same level as the conftest.py). Again, when run locally, it works just fine so I cannot figure out why CircleCI can't see it too. It says no such file or directory. Any suggestions would be greatly appreciated. -
How to implement Disable/Enable edit functionality on django admin change_form with simple action button?
I am trying to create a django change_form as by default are not editable, but editable only if user clicks custom action button. I mean by default; def has_change_permission(self, request, obj=None): return False Created custom action button to achieve this (with extending submit_line.html) {% extends "admin/submit_line.html" %} ... <input type="submit" value="Enable/Disable Edit" name="enableDisableEdit" /> Then I thought, i should do something with overriding response_change function. But couldn't def response_change(self, request, obj): if 'enableDisableEdit' in request.POST: ...Some code to enable disable edit Any idea? Thanks! -
No CustomerOrder matches the query
I am trying the generate PDF's for customers who successfully pays for an item but I keep getting this error. No CustomerOrder matches the query Below are my codes. views.py @staff_member_required def admin_order_pdf(request, order_id): order = get_object_or_404(CustomerOrder, id=order_id) html = render_to_string('orders/pdf.html', {'order': order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = f'filename=order_{order_id}.pdf' weasyprint.HTML(string=html).write_pdf(response, stylesheets=[weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css')]) return response urls.py urlpatterns = [ path('', views.order_payout, name='order_payout'), path('admin/order/<int:order_id>/pdf', views.admin_order_pdf, name='admin_order_pdf'), path('confirm/', views.confirm_order, name='confirm_order'), ] -
Django ORM: Count, Max, and retrieve field associated with max
In my situation there's a table with 3 fields A, B, and C. I want to group by A, and also store how many occurrences there are of each distinct A (Count). I also want to retrieve the max B for each A group and the C that is associated with the max B for each group. Only C has no duplicates. Does anyone know how to do write such a query using Django ORM? -
Django AssertionError: 404 != 200
I have a Class based view: class PromocionListView(ListView): model = Promocion and this url path: urlpatterns = [ path('promocion/list', PromocionListView.as_view(), name='promocion_list')] so i made the following test: class PromocionTests(TestCase): @classmethod def setUpTestData(cls): cls.promocion = Promocion.objects.create(fecha_de_inicio = date(2022,7,6),duracion = 90) def test_url_exists_at_correct_location(self): response = self.client.get('promocion/list') self.assertEqual(response.status_code, 200)` but it is showing the error: AssertionError: 404 != 200. Does anything knows why this is happening? I googled it a lot but I couldn't find an answer -
When I run a docker image it's stopped without giving any error?
There is my Dockerfile: Click here to see the image . This is the shell script: Click here to see the image . There is the output while image is running: Click here to see the image .As you see it's stopped there, after the model had train, but the container is kept starting. . I'm witing for output like this, to be able to use my api: Click here to see the image . Note: I don't know why nltk is dowloadning after the training, because in when i run the project from my host is the first thing, and the model can't train without ntlk.