Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to do django transaction to a set of code , including queries as well as local operations
permissionIds = [1,2...] try: with transaction.atomic(): RolePermissionMap.objects.bulk_create([ RolePermissionMap(role_id=role.id, permission_id=id) for id in permissionIds]) rolePermissionsMap[roleId] = permissionIds # map should NOT update if the insert fails return Response({"ok": 1}, status=200) except: return Response({"ok": 0} In my code , I need to create multiple raws at a time, incase one of the given permission Id fails, it shouldnot do the next step , which storing some data in to a dict.(its not a db transaction, so it cannot rollback). how can I do it efficiently? -
django_jsonforms are not displayed in the browser
I want to run a ready python project in virtual environment. When I run the project I face no error. And when I write this in the terminal "py manage.py runserver" , I can see just a label of the project in the browser and forms are not being shown. I searched a lot, this project is almost complete and is working in other systems. I don't know what changes I should apply to the project. -
Django Model Translation with django rest framework not working
I have successfully implemented models translation and i notice it is working like i can add content in multiple languages from the Django admin but when i implemented in django rest framework, it doesnt work for my expected language, I have successfully sent header for language, translatoin working fine except model translation. I found this solution: Model translation in Django Rest Framework and I found it is good but not getting how to implement this. This is my views class BlogViewSets(ModelViewSet): serializer_class = BlogSerializer lookup_field = 'slug' def get_queryset(self): return BlogPage.objects.all() Can anyone tell me please how can implement this advised solution? Model translation in Django Rest Framework Not getting any way to implement this. -
How to exclude verbose_name_plural field from migration?
Good afternoon! I'm using the verbose_name_plural dynamic field to show some up-to-date information in the admin panel. Django version: 4.1 The model looks like this: from django.utils.functional import lazy from django.utils.translation import gettext_lazy as _ class Post(models.Model): # ... class Meta: verbose_name = 'Post' verbose_name_plural = lazy(lambda: _('Posts ({})').format(Post.....count()), str)() I don't remember where I found this option to display some information, but it works great, except that every time the value changes and the command to create migrations is run, I get something like this: from django.db import migrations class Migration(migrations.Migration): operations = [ migrations.AlterModelOptions( name='post', options={'verbose_name': 'Post', 'verbose_name_plural': 'Posts (123)'}, ), ] I found this option: https://stackoverflow.com/a/39801321/2166371 But I don’t know how relevant it is and why a class that is not used is imported there -
Update or create async Django ORM instance
As the Django docs states, it supports async using a custom interface, with methods like get being aget. I'm trying to save my instances using update_or_create method and I was wondering how can I convert this to an async context. -
Check If Timeslot lies in between provided time range
I am trying to implement Academic Time Table Generator using django framework, in which I am allocating lectures and labs to particular time slots randomly. So, The timing for academic study starts from 9:30 AM - 4:00 PM, in which there will be a break at 12:30 PM - 1:00 PM lectures have 1 hour of Time slots and the labs have 2 hours of time slots. As I am allocating lab or lect randomly there is a problem when lab is selected at 11:30 then by default it is taking 2 hours for lab so it will allocate time for 11:30 AM - 1:30 PM. So, I am looking for a way to check if break time collides with lab time and if it is then allocate lecture instead. if inc <= shift_1.to_time and (inc <= shift_1.break_from_time): . . lab allocating function . . else: . . lect allocating function . . Here, inc - incremented hours ( for lab current time slot + 2) shift1.to_time - Ending Time for day ( 4:00 PM ) shift_1.break_from_time - Starting time for break ( 12:30 PM ) The if clause here is not useful as I am just checking if inc … -
Djongo Error: Keyword: FAILED SQL: SELECT %(0)s AS "a" FROM "testapp_test_db" WHERE "testapp_test_db"."id" = %(1)s LIMIT 1 Params: (1, 1)
I have created two models in Django. The one is Test_DB and the other is ForeignKey_Test. The later models has a foreign key field which is referring to the Test_DB. When I tried to enter data from the the Django's default admin panel, I got the following error. The above exception ( Keyword: FAILED SQL: SELECT %(0)s AS "a" FROM "testapp_test_db" WHERE "testapp_test_db"."id" = %(1)s LIMIT 1 Params: (1, 1) Version: 1.3.6 Sub SQL: None FAILED SQL: None Params: None Version: None) was the direct cause of the following exception: What I am concluding that while parsing the SQL, Djongo expects two parameters to be passed. But currently it is being only one passed and that is the id. Can somebody tell me what's wrong here? I can share any of the snippet of my project here. Models class Test_DB(models.Model): name = models.CharField(max_length=50) class ForeignKey_Test(models.Model): name = models.CharField(max_length=50) test_id = models.ForeignKey(to='Test_DB', on_delete=models.CASCADE) My database is in MongoDb and I am using Djongo. pip freeze asgiref==3.5.2 backports.zoneinfo==0.2.1 certifi==2022.9.24 charset-normalizer==2.1.1 coreapi==2.3.3 coreschema==0.0.4 Django==4.1.1 django-cors-headers==3.13.0 djangorestframework==3.14.0 djangorestframework-simplejwt==5.2.0 djongo==1.3.6 drf-yasg==1.21.3 idna==3.4 inflection==0.5.1 itypes==1.2.0 Jinja2==3.1.2 MarkupSafe==2.1.1 packaging==21.3 PyJWT==2.5.0 pymongo==3.12.3 pyparsing==3.0.9 pytz==2022.2.1 PyYAML==6.0 requests==2.28.1 ruamel.yaml==0.17.21 ruamel.yaml.clib==0.2.6 sqlparse==0.2.4 uritemplate==4.1.1 urllib3==1.26.12 -
Django Create or update with unique together values
I'm trying to make an attendance system in the frontend I retrieve a list of users which the request.user can take attendance of, I'm using CreateAPIView but this won't get me the desired effect as I want the request.user to be able to toggle between Absent, Present, and on_leave even after the entry has been created on the first request i have seen questions and answers about create or update here but i couldn't use them so any help would be appriciated this is my view.py class AttendanceListCreateAPIView(CreateAPIView): permission_classes = [IsTeacher_Student] queryset = Attendance.objects.all() serializer_class = AttendanceSerializer def post(self, request, *args, **kwargs): user = request.user data = request.data serializer = AttendanceSerializer(data=data) if serializer.is_valid(): data_user = serializer.validated_data['user'] ## validation return Response({"message": "Something is wrong, maybe you have already taken attendance for this user"}, status=status.HTTP_400_BAD_REQUEST) my serializer.py class AttendanceSerializer(serializers.ModelSerializer): date = serializers.HiddenField(default=timezone.now) leave_reason = serializers.CharField(required=False, default="") class Meta: model = Attendance fields = ['user', 'presence', 'leave_reason', 'date'] extra_kwargs = { 'user': {'required': True}, 'presence': {'required': True}, 'leave_reason': {'required': False}, } validators = [ UniqueForYearValidator( queryset=Attendance.objects.all(), field='user', date_field='date', message=("You have already taken the attendance") ) ] def create(self, validated_data): instance = Attendance.objects.create( user=validated_data['user'], presence=validated_data['presence'], leave_reason=validated_data['leave_reason'], date=validated_data['date'], ) instance.save() return instance desired effect the … -
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)