Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display only search results in Django?
I have created a page where all objects are displayed. Also, there is a search. If you enter a query into a search, the page will display the search results. I would like nothing to be shown on the page by default, only the search bar. And only after entering a value in the search, the page shows the search results. How to do it? Home.html <div class="headtext"> <form method="GET" action="{% url 'search' %}"> <input type="search" type="text" name="q" prequired placeholder="Put appnumber"> <button type="submit">Find</button> </form> </div> <div> {% for application in object_list %} <div> <p>Application: {{ application.appnumber }}, status: {{ application.status }}</p> </div> {% endfor %} </div> Urls.py from django.urls import path from .views import HomeView, Search urlpatterns = [ path('', HomeView.as_view(), name="home"), path('search/', Search.as_view(), name="search"), Views.py class HomeView(ListView): model = Application template_name = 'home.html' class Search(ListView): template_name = 'home.html' def get_queryset(self): return Application.objects.filter(appnumber__icontains=self.request.GET.get("q")) def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context["q"] = self.request.GET.get("q") return context -
error: "Refused to apply style from ./static/css/main.739.css' because its MIME type ('text/html') is not a supMIME type, and strict MIME checking
I have a problem that I have wasted too much time on it. I would really appreciate some help. I try to serve my django (react at front) staticfiles with AWS s3. When I in DEBUG=True everything works fine (Due to the fact that it really uses the local files and not S3), but when I move to DEBUG=False I get the error and white screen: Refused to apply style from 'http://localhost:8000/static/css/main.7f770239.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. Refused to execute script from 'http://localhost:8000/static/js/main.c2ee425b.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. and the network: Request URL: http://**localhost:8000**/static/js/main.c2ee425b.js Request Method: GET Status Code: 200 OK Remote Address: 127.0.0.1:8000 Referrer Policy: no-referrer-when-downgrade 2 NOTES: [1] It looks like is still try to serve from my local host and not from s3, and I checked all the appropriate configurations (see below). [2] I have no problem with the media files, I manage to upload files and view them using s3 bucket. I've followed quite a few guides, and no configuration has worked so far, currently I'm working like this: from storages.backends.s3boto3 import S3Boto3Storage … -
CRLF Injection with python
How can I write a simple web app that includes the CRLF vulnerability with python to test the vulnerability described here? https://www.geeksforgeeks.org/crlf-injection-attack/ I want to know if it is possible to do this with python. -
Duplicate, copy the values from the first row (model table) for N number of rows?
I have a Django model table. In which the content is only one - the first row of the table. But I need to duplicate - this first single row. I need to fill 20 (for example, N number of rows of the model table) with the same values as from the first row of the model table. How can you duplicate, copy the values from the first row (model table) for N number of rows? -- before 0 2023-01-02 10:00:00 60.37 50.37 13.651 12.189 after 0 2023-01-02 10:00:00 60.37 50.37 13.651 12.189 1 2023-01-02 10:00:00 60.37 50.37 13.651 12.189 2 2023-01-02 10:00:00 60.37 50.37 13.651 12.189 3 2023-01-02 10:00:00 60.37 50.37 13.651 12.189 4 2023-01-02 10:00:00 60.37 50.37 13.651 12.189 -
I'm having a hard time using Django with Heroku Connect. I'm unable to update salesforce tables from Django
I have a django app on heroku. I added Heroku Connect to the postgresql database and mapped few objects. This created a new schema called 'salesforce'. Here is the issue: Heroku connect created a table called 'building__c' which represents the custom object in salesforce. When I edit the 'building__c' table manually from pgAdmin4, it updates back to salesforce with no isses. I created a model in django to represent the 'building__c' table. **I was able to view the data in Django easily. I can read all the data just fine. However, when I try to modify the data, it doesn't let me and I get this error. ** class BuildingC(models.Model): name = models.CharField(max_length=80, blank=True, null=True) ru_id_c = models.CharField(db_column='ru_id__c', max_length=16, blank=True, null=True) # Field renamed because it contained more than one '_' in a row. isdeleted = models.BooleanField(blank=True, null=True) systemmodstamp = models.DateTimeField(blank=True, null=True) street_adress_c = models.CharField(db_column='street_adress__c', max_length=100, blank=True, null=True) # Field renamed because it contained more than one '_' in a row. state_c = models.CharField(db_column='state__c', max_length=5, blank=True, null=True) # Field renamed because it contained more than one '_' in a row. zipcode_c = models.CharField(db_column='zipcode__c', max_length=19, blank=True, null=True) # Field renamed because it contained more than one '_' in a row. createddate … -
How to use Django's `full_clean` using a non-default database
Note, this is a rewrite of a deleted question. I'd have edited it, but there were no comments, so I never even knew it was deleted until I went to add new details today. Background: I'm modifying our code-base to make use of multiple databases for validation of user-submitted load files. This is for automated checks of that user data so that they can fix simple issues with their files, like checks on uniqueness and such. Our original code (not written by me) has some fundamental issues with loading. It had side-effects. It should have used transaction.atomic, but didn't and simply adding it broke the codebase, so while a refactor will eventually fix that properly, to reduce effort, I created a second database (with the alias "validation") and inserted .using(db) and .save(using=db) in all the places necessary so that loading data can be tested without risking the production data. Everything works as expected with the 2 databases except calls to full_clean(). Take this example: new_compound_dict = { name="test", formula="C1H4", hmdb_id="HMBD0000001", } new_compound = Compound(**new_compound_dict) new_compound.full_clean() new_compound.save(using="validation") It gives me this error: django.core.exceptions.ValidationError: {'name': ['Compound with this Name already exists.'], 'hmdb_id': ['Compound with this HMDB ID already exists.']} I event get … -
django 2.1 change last_login null
I have some new users for my graphite site. They're just trying to login and keep running into this issue: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 486, in get_or_create return self.get(**lookup), False File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 399, in get self.model._meta.object_name django.contrib.auth.models.User.DoesNotExist: User matching query does not exist. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 71, in execute return self.cursor.execute(query, args) File "/usr/local/lib/python3.6/site-packages/pymysql/cursors.py", line 148, in execute result = self._query(query) File "/usr/local/lib/python3.6/site-packages/pymysql/cursors.py", line 310, in _query conn.query(q) File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 548, in query self._affected_rows = self._read_query_result(unbuffered=unbuffered) File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 775, in _read_query_result result.read() File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 1156, in read first_packet = self.connection._read_packet() File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 725, in _read_packet packet.raise_for_error() File "/usr/local/lib/python3.6/site-packages/pymysql/protocol.py", line 221, in raise_for_error err.raise_mysql_exception(self._data) File "/usr/local/lib/python3.6/site-packages/pymysql/err.py", line 143, in raise_mysql_exception raise errorclass(errno, errval) pymysql.err.IntegrityError: (1048, "Column 'last_login' cannot be null") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.6/site-packages/django/utils/deprecation.py", line 90, in __call__ response = self.process_request(request) File "/usr/local/lib/python3.6/site-packages/django/contrib/auth/middleware.py", line 78, in process_request user = auth.authenticate(request, remote_user=username) File "/usr/local/lib/python3.6/site-packages/django/contrib/auth/__init__.py", line 73, in … -
I'm trying to figure out how to run a docker container with a django project
I've been trying to make a docker container with a django project and have tried different solutions I've found but none of them work. My current Dockerfile So far I've tried different youtube tutorials for setting up python and django docker containers but none of them have worked ending me up with different errors. -
How to export querysets into Model Django?
How to export two querysets into one Model Django? How can I write values from two querysets to the columns of the model table through a loop or in some other way? -- for all rows in querysets: queryset_1 last_row = queryset_1.last() values_1 = last_row.name_1 values_2 = last_row.name_2 new_entry = Model_3(name_1=values_1, name_2=values_2) new_entry.save() queryset_2 last_row = queryset_2.last() values_3 = last_row.name_3 values_4 = last_row.name_4 new_entry = Model_3(name_3=values_3, name_4=values_4) new_entry.save() -- queryset_1_min = queryset_1_filter.filter(pk__lte=limit) queryset_2_min = queryset_2_filter.filter(pk__lte=limit) queryset_3_min = queryset_3_filter.filter(pk__lte=limit) for item in queryset_1_min: values_1 = item.datetime values_2 = item.temper_1 values_3 = item.temper_2 values_4 = item.g_rashod values_5 = item.temper_nv new_entry = Model_upload_summ(datetime=values_1, temper_1=values_2, temper_2=values_3, g_rashod=values_4, temper_nv=values_5) # entry = Model_upload_summ(**item) new_entry.save() transaction.commit() -- sqlite3.IntegrityError: NOT NULL constraint failed: application_model_upload_summ.temper_1_gvs -- and add several data from queryset_2_min into Model_upload_summ -
how to add multiple domains into DJANGO_ALLOWED_HOSTS as an environment variable
in django 4.1 application I'm trying to add several allowed hosts in my .env fiel as an environment variable like this -> DJANGO_ALLOWED_HOST=synapse-developmentcenter.am www.synapse-developmentcenter.am 127.0.0.1 localhost 0.0.0.0 but only first domain working correctly and after echo $DJANGO_ALLOWED_HOST shows only synapse-developmentcenter.am and here is my settings.py line addressing .env file. running cat .env showing coorectly and when trying to export it again only first domain getting there for the rest it shows -> bash: export: `127.0.0.1': not a valid identifier like this ALLOWED_HOSTS = [] if not DEBUG: ALLOWED_HOSTS += os.environ.get('DJANGO_ALLOWED_HOST').split(' ') I tried chane variable types to this -> [DJANGO_ALLOWED_HOST=synapse-developmentcenter.am www.synapse-developmentcenter.am 127.0.0.1 localhost 0.0.0.0] or ["DJANGO_ALLOWED_HOST=synapse-developmentcenter.am www.synapse-developmentcenter.am 127.0.0.1 localhost 0.0.0.0"] even like this -> DJANGO_ALLOWED_HOST="synapse-developmentcenter.am www.synapse-developmentcenter.am 127.0.0.1 localhost 0.0.0.0" but neihet of them worked -
Why My PDF Files get corrupted when I am uploading them through Django admin site?
I I am creating a simple web page for downloading pdf files, file uploads are only admin side. This is my model for pdf file. As I download the file from front side, the file is corrupted, urls are connfigured properly, the file get's corrupted while django is saving my model, I assume this from the fact that my staticfiles also contain a corrupt version of file. class Paper(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE) display_name = models.CharField(max_length=200) source_file = models.FileField() -
How to combine Django TestCase test wit PyTest test in one tests.py file?
I have code in tests.py (Django tests): class MyTest1(TestCase): ... class MyTest2(TestCase): ... class MyTest3(TestCase): ... as well as few pytest tests (in regular functions with proper pytest decorators), but Django after using command: python manage.py test is not taking into account pytest tests. This tests are not used. What should I change in my tests.py file? How to deal with two types of tests? -
Raise 404 exception in django when using Login Required
I have little problem with django when i want use login required i get error 404, i use mysql database and after I create user in database, this problem is occuring with login page. My code is: @login_required(login_url=reverse_lazy("login")) def login_user(request): cursor = connections['default'].cursor() if request.method == "GET": return render(request,'html/login_user.html') if request.method == "POST": usrn = request.POST['username'] password = request.POST['password'] if cursor.execute(f"SELECT username,password FROM users WHERE username='{usrn}' AND password='{password}';"): return redirect("home_login") else: messages.warning(request,"Username/Password incorrect,please try again.") return render(request,'html/login_user.html') from django.contrib import admin from django.urls import path from .views import home,product,contact,about,login_user,register_user,product_info,cart,home_login urlpatterns = [ path('', home,name='home'), path('product',product,name='product'), path('contact',contact,name='contact'), path('about',about,name='about'), path('account/login/',login_user,name='login'), path('register',register_user,name='register'), path('product_info',product_info,name='product_info'), path('cart',cart,name='cart'), path("home",home_login,name="home_login") ] -
How to sort products in django?
There is a page with products. Can you tell me how to make sure that the goods are sorted in the way that the user chose in the form?That is, there was a button that the user clicked on and could sort the goods, for example, from the cheapest to the most expensive, and vice versa, then he could sort the goods by novelty, etc Water code: `model.py class Product (models.Model): title = models.CharField(max_length=50,verbose_name='Заголовок') slug = models.SlugField(max_length=255,unique=True,db_index=True,verbose_name='URL') content = models.TextField(blank=True,verbose_name='Общее описание') structure = models.TextField(blank=True,verbose_name='Состав') care = models.TextField(blank=True,verbose_name='Уход') photo = models.ImageField(upload_to="photo/%Y/%m/%d/",blank=True,verbose_name='Фото') photo2 = models.ImageField(upload_to="photo/%Y/%m/%d/",blank=True, verbose_name='Фото2') photo3 = models.ImageField(upload_to="photo/%Y/%m/%d/",blank=True, verbose_name='Фото3') time_create = models.DateTimeField(auto_now_add=True,verbose_name='Время создания') time_update = models.DateTimeField(auto_now=True,verbose_name='Время изменения') price = models.DecimalField(max_digits=15,decimal_places=2,verbose_name='Цена') available = models.BooleanField(default=True,verbose_name='Наличие') is_published = models.BooleanField(default=True,verbose_name='Публикация') prod_sub_category = models.ForeignKey('Category', on_delete=models.DO_NOTHING,verbose_name='Выберите категорию') > subproduct = models.ForeignKey('Subcategory', on_delete=models.DO_NOTHING,verbose_name='Выберите подкатегорию')` -
when i runserver (python manage.py runserver) this error is raised: TypeError: a bytes-like object is required, not 'str'
I tried deploying my django postgresql app using Render. The deploy worked but no data is being returned. Also, when I try to load seed data or run the server from my directory the following error is thrown: Traceback (most recent call last): File "/Users/xxx/xxx/xxx/xxx/manage.py", line 22, in <module> main() File "/Users/xxx/xxx/xxx/xxx/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/xxx/.local/share/virtualenvs/xxx/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/Users/xxx/.local/share/virtualenvs/xxx/lib/python3.9/site-packages/django/core/management/__init__.py", line 386, in execute settings.INSTALLED_APPS File "/Users/xxx/.local/share/virtualenvs/xxx/lib/python3.9/site-packages/django/conf/__init__.py", line 87, in __getattr__ self._setup(name) File "/Users/xxx/.local/share/virtualenvs/xxx/lib/python3.9/site-packages/django/conf/__init__.py", line 74, in _setup self._wrapped = Settings(settings_module) File "/Users/xxx/.local/share/virtualenvs/xxx/lib/python3.9/site-packages/django/conf/__init__.py", line 183, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/local/Cellar/python@3.9/3.9.13_1/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 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/Users/xxx/xxx/xxx/xxx/project/settings.py", line 114, in <module> 'default': dj_database_url.parse(os.environ.get('DATABASE_URL'), conn_max_age=600), File "/Users/xxx/.local/share/virtualenvs/xxx/lib/python3.9/site-packages/dj_database_url.py", line 94, in parse if "?" in path and not url.query: TypeError: a bytes-like object is required, not 'str' here is part of my settings.py: DATABASES = { 'default': dj_database_url.parse(os.environ.get('DATABASE_URL'), conn_max_age=600), } I've also tried: DATABASE_URL = os.environ.get('DATABASE_URL') DATABASES = { … -
How to get multiple field values, when a foreign key is called in django
I have a Attendance model class Attendance(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE) date = models.DateField() day = models.CharField(max_length=10) in_time = models.CharField(max_length=5) out_time = models.CharField(max_length=5) Here is the Employee model class Employee(models.Model): emp_id = models.CharField(max_length=10,primary_key=True) emp_type = models.CharField(max_length=50) name = models.CharField(max_length=100) epf_no = models.CharField(max_length=10) nic_no = models.CharField(max_length=15) appoinment_date = models.DateField() termination_date = models.DateField() address = models.CharField(max_length=50) mobile_no = models.CharField(max_length=15) email = models.EmailField(max_length=50) bank_name = models.CharField(max_length=50) bank_branch = models.CharField(max_length=20) bank_acc_name = models.CharField(max_length=20) bank_acc_no = models.CharField(max_length=15) active_status = models.BooleanField(default=True) I'm getting data from Attendance model attendance_record = Attendance.objects.filter(date = date).values() Here for the employee attribute I'm automatically getting the emp_id field.But I want to get the name field as well How to do it.? -
what can i do to send json.dumps as list in django channels?
I want to take the player list from the room and send it to react with the room websocket(django channels). I need a list to handle all users but websocket turns a string like this this is not array pure string! [{"model": "api.roomusers", "pk": 396, "fields": {"user_name": "kevin", "score": null}}] Here is my consumers.py roomUsers = serializers.serialize( "json", models.RoomUsers.objects.filter(room=isRoomExist), fields=('user_name', 'score')) async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'user_data', 'roomUsers': roomUsers, } ) def user_data(self, event): roomUsers = event["roomUsers"] async_to_sync(self.send(text_data=json.dumps( {"type": "user_data", "roomUsers": roomUsers}))) react side case "user_data": console.log(data.roomUsers); console.log(typeof(data.roomUsers)); break; **react side turn says data.roomUsers is string not an array. ** I am stuck here and I don't have an opinion to solve this situation -
Django Rest Framework how to display related models as one json file
I have a few different models with a fact table of scenarios and 6 dimension tables that relate to it below as examples: class fScenario(models.Model): #Variables scenarioId = models.IntegerField(primary_key=True) description = models.CharField(max_length=100) def __str__(self): return str(self.scenarioId) def get_absolute_url(self): return reverse('scenario-detail', args=[str(self.scenarioId)]) class Meta: ordering = ['scenarioId'] class dADA(models.Model): #Variables scenarioId = models.ForeignKey(fScenario, on_delete=models.CASCADE) dateTimeId = models.DateTimeField('ADA Time/Date') latitutde = models.FloatField(default=0) longitude = models.FloatField(default=0) instanceType = models.CharField(max_length=50, default='ADA') def __str__(self): return f'{self.scenarioId}, {self.instanceType}' class Meta: ordering = ['dateTimeId'] serializers.py class fScenarioSerializer(serializers.ModelSerializer): class Meta: model = fScenario fields = ['scenarioId', 'description'] class dADASerializer(serializers.ModelSerializer): scenarioId = fScenarioSerializer(read_only=True) class Meta: model = dADA fields = ['scenarioId', 'dateTimeId', 'latitutde', 'longitude', 'instanceType'] urls.py router = routers.DefaultRouter() router.register(r'fScenario', views.fScenarioViewSet) router.register(r'dADA', views.dADAViewSet) urlpatterns = [ path('', include(router.urls)), views.py class fScenarioViewSet(viewsets.ModelViewSet): queryset = fScenario.objects.all() serializer_class = fScenarioSerializer class dADAViewSet(viewsets.ModelViewSet): queryset = dADA.objects.all() serializer_class = dADASerializer I'm using rest framework view sets and I currently can see in my API separate fScenario and dADA views but cant figure out how to link the dADA to the fScenario view on one page. -
How to change styles for an import form (django-import-export)?
How to change styles for an import form (django-import-export)? -
DRF Q Filter string working in Django shell_plus, but not in django-filter code
I have a DRF project where I use Q filters to filter the query set. The search value will be used to search a string field "name" and tested if it is an integer and then tested if it is eq to "port" or part of a range defined by "port" and "port_end". I need to modify the Q filter based on some conditions, so I thought it would be easy to define the query based on conditions and use it in the filter. I was thinking that there might be an issue that the value is a string and the field in the DB an integer. But that is not the case I also tried to have fixed values in the string as integer and string, but that was not the issue. Also a int(value) did not change anything. If I do this in the Django shell_plus, then I get proper results: >>> value = "22" >>> query = Q(name__icontains=value)|Q(port__exact=value)|(Q(port__lte=value)&Q(port_end__gte=value)) >>> items = MyObject.objects.filter(query) >>> print(items) If I do the same in my DRF filter code then the "items" query has only matches for the name field. query = Q(name__icontains=value)|Q(port__exact=value)|(Q(port__lte=value)&Q(port_end__gte=value)) items = queryset.filter(query) I have remove the filter on … -
Delete rows or sort model if column value is less than given value?
I have a table model. In one column of the table, the data is in the form - date-time. Dates may vary slightly. How to compare the column of the model table through a loop or in some other way and (provided that the date in the column is less than a certain given date) delete the current row? Delete those rows from the model if the value in the column (date time) of the table is less than the given one. -- "value" = 2023-01-04 10:00:00 -- queryset_1_sorted = Model_1.objects.order_by("datetime" < "value") -- datetime temper_1 temper_2 g_rashod temper_nv 0 2023-01-02 10:00:00 58.13 49.35 70.520 1.4 1 2023-01-02 11:00:00 57.44 49.12 89.805 1.4 2 2023-01-02 12:00:00 57.82 49.30 89.187 1.4 3 2023-01-02 13:00:00 58.08 49.62 89.079 1.4 4 2023-01-02 14:00:00 58.20 49.77 89.081 2.1 225 2023-10-02 19:00:00 65.67 53.90 87.998 -7.6 226 2023-10-02 20:00:00 66.80 54.98 87.970 -8.1 227 2023-10-02 21:00:00 67.37 55.53 87.946 -8.1 228 2023-10-02 22:00:00 67.76 55.87 87.973 -8.1 229 2023-10-02 23:00:00 68.02 56.09 87.942 -8.1 -
Test one detail page of django website using TestCase
I got error while running tests: p_pattern = url_pattern.pattern.regex.pattern AttributeError: 'int' object has no attribute 'pattern' while try to test "detail pages", all other tests, so far, works fine. I have used in tests.py syntax like: response = self.client.get(reverse('employee_detail', (3,))) assert response.status_code == 200 and: response = self.client.get('/employee-detail/3/') self.assertEqual(response.status_code, 200) My urls.py corresponding line is: path("employee-detail/<int:employee_id>/", views.EmployeeDetailView.as_view(), name='employee_detail'), My tests failed on both examples. -
Is there a way I could send a book primary key to a url in another django app?
I want to make a book marketing web app using Django and I want to show the book details using another Django app, and I need the book primary key in the details app. my question is what is the best way to pass the book pk to the detail URL defined in the book_details app. this is my home urls.py: from django.urls import path, include from .views import * urlpatterns = [ path('', home_page_view, name='home'), path('books/', include('book_details.urls'), name='books'), ] and this is my details app (book_details) urls.py: from django.urls import path, include from .views import * app_name = 'book_details' urlpatterns = [ path('<int:pk>/', book_details_view, name="book_detail") ] I tried doing it like this in the home app template and it does not work: <a href="{% url 'book_details:book_detail' post.pk %} " class="book-card-link"> the Error: Reverse for 'book_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['books/(?P[0-9]+)/\Z'] Sorry if my question is not very clear, it's my first time asking a question here, Thanks. -
sending json object to Django framework returns a 500 code error
I am sending an object using AJAX to a Django view. The data I am sending is mouse movement which is sent every 10 seconds to the server to be saved. Now, I have no problem reading my data from the client and server sides. The data gets saved in the database, but I get a 500 error message every time the function sends to the server gets executed. I tried to use fetch and got this error message: POST error: SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON I searched about this error, and my understanding is that the problem is with the data type, but I am unsure how I can trace the problem and fix it. Could someone help me troubleshoot this issue? here is my js function: var target_id = ''; var eventsLog = {"mouse": []}; function logMouse(event){ target_id = event.target.id; currDate = new Date() start_time = currDate.getHours() + ':' + currDate.getMinutes() + ':' + currDate.getSeconds() + ':' + currDate.getMilliseconds(); var insert = [start_time, target_id]; (eventsLog.mouse).push(insert); } var timesPerSecond = 5; var wait = false; $(document).on('mousemove', function (event) { if (!wait) { logMouse(event); wait = true; setTimeout(function () { wait = false; }, 1000 … -
My custom widget does not get rendered when the field is added using a parameter
Why is my widget not rendered? The render methond of SiteNameInputWidget is never hit. from django import forms from django.template import loader from django.utils.safestring import mark_safe class SiteNameInputWidget(forms.TextInput): template_name = 'sites/widgets/SiteNameInputWidget.html' def __init__(self, attrs=None, prefix_for=None): super().__init__(attrs) self.prefix_for = prefix_for def render(self, name, value, attrs=None, renderer=None): super().render(name, value, attrs, renderer) class SiteNameForm(forms.Form): def __init__(self, prefix_for=None, *args, **kwargs): super(SiteNameForm,self).__init__(args,kwargs) self.fields['site_prefix'] = forms.CharField(widget=SiteNameInputWidget(prefix_for=prefix_for)) If I define the Form like this (an don't pass prefix_for in the constructor) it gets called. class SiteNameForm(forms.Form): site_prefix = forms.CharField(widget=SiteNameInputWidget(prefix_for='TEST'))