Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Request in test APIClient fails after authenticating twice
After upgrading to django 5, our test suite started showing odd behavior. We are using DRF's APIClient and authentication does not work as expected anymore. Certain API requests return rest_framework.exceptions.NotAuthenticated with status code 403 (by the way, if someone could explain why this status is 403 and not 401, I'd appreciate). This is seemingly arbitrary. Among 2 requests to views which are implemented identically in terms of user permissions etc, one returns 403 during testing only. Executing the same calls in Postman does not reproduce the error. Thus, some of the exact same test cases which used to pass under django 4 do not pass anymore under django 5 due to above error. I did not manage to reproduce these cases in a minimal example. What I did reproduce however, is the following: client.force_authenticate(user) client.get(url) # the user does not have permissions. response is 403, as expected client.force_authenticate(None) # "log out" user.user_permissions.add(permission) client.force_authenticate(user) response = client.get(url) # the now has permissions. response 200 is expected assert response.status_code == 200 # response status is 403 Package versions are django==5.0.3 djangorestframework==3.15.0 pytest==7.4.3 pytest-django==4.7.0 I have made a minimal project where this can be observed. As far as I managed to test it, … -
Uncaught TypeError: $.ajax is not a function in jQuery
I'm encountering an issue with jQuery's $.ajax function in my web application. When I try to make an AJAX request using $.ajax, I'm getting the error "Uncaught TypeError: $.ajax is not a function" in the browser console. Here's the relevant code snippet: $.ajax({ url: "/add-to-wishlist", data: {"id": product_id}, dataType: "json", beforeSend: function(){ console.log("Adding to wishlist"); }, success: function(response){ this_val.html("👍🏼"); if (response.bool === true) { console.log("Added to wishlist"); } }, error: function(xhr, errmsg, err){ console.log(xhr.status + ": " + xhr.responseText); console.log(errmsg); } }); I've ensured that jQuery is properly included in my HTML file before including my JavaScript file. However, I'm still encountering this error. Could anyone help me understand why I'm getting this error and how to resolve it? Any insights or suggestions would be greatly appreciated. Thank you! I'm facing a problem with adding products to the wishlist feature in my Django web application. Here's the relevant: View (add_to_wishlist): def add_to_wishlist(request): product_id = request.GET['id'] product = Product.objects.get(id=product_id) context = {} wishlist_count = wishlist.objects.filter(product=product, user=request.user).count() print(wishlist_count) if wishlist_count > 0: context = { "bool": True } else: new_wishlist = wishlist.objects.create( product=product, user=request.user ) context = { "bool": True } return JsonResponse(context) HTML Button: <button class="btn-action" data-product-item="{{ p.id }}"> <ion-icon name="heart-outline"></ion-icon> … -
How to optimize and implement infinite comments through prefetch with django orm?
I'm implementing the comment function and I can leave a big message in the comments. It was easy to implement the function, but it's causing n+1 queries. Please tell me how to solve this problem python Prefetch( 'comments', queryset=PlaceReviewComment.objects.select_related( 'user', ).prefetch_related( Prefetch( '_comments', queryset=PlaceReviewComment.objects.select_related( 'user', 'parent_comment', ).prefetch_related( '_comments', '_comments__user', ).filter( removed_at__isnull=True ), to_attr='child_comments' ), ).filter(parent_comment=None, removed_at__isnull=True), to_attr='_comments' ), ).filter( id=review_id, If I do this, I'll only get one depth's comment Should I implement a function that does prefetch as much as depth? But I also think to check that there is a _comment and add prefetch, but I don't know how -
No data posted to Django rest api when button is pressed
I have a form with text inputs, and I have created a button as well which when pressed, should post the input field data into a Django Api. But when I press the button, nothing happens and there seems to be no error as well. This is sample from my code: class MyForm extends StatefulWidget { @override _MyFormState createState() => _MyFormState(); } class _MyFormState extends State<MyForm> { final String url = 'http://127.0.0.1:8000/api/?format=json'; final TextEditingController nameController = TextEditingController(); final TextEditingController phoneController = TextEditingController(); final TextEditingController purposeController = TextEditingController(); final TextEditingController addressController = TextEditingController(); final TextEditingController visiteeController = TextEditingController(); final TextEditingController dateController = TextEditingController(); String result = ''; Future<void> _postDataToDjango() async { try { final response = await http.post(Uri.parse(url), headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode(<String, dynamic> { 'visitor_name': nameController.text, 'visit_date': dateController.text, 'Time_in': (TimeInputField()._selectedTime).toString(), 'Time_out': Null, 'Department': (DropdownMenuExample().dropdownValue).toString(), 'Visitee_name': visiteeController.text, 'Address': addressController.text, 'Phone': phoneController.text, 'Purpose_of_visit': purposeController.text }), ); if (response.statusCode == 201) { final responseData = jsonDecode(response.body); print('Post successful'); setState(() { result = 'id: ${responseData['id']}\nvisitor_name: ${responseData['visitor_name']}\nvisit_date: ${responseData['visit_date']}\nTime_in: ${responseData['Time_in']}\nTime_out: ${responseData['Time_out']}\nDepartment: ${responseData['Department']}\Visitee_name: ${responseData['Visitee_name']}\nAddress: ${responseData['Address']}\nPhone: ${responseData['Phone']}\nPurpose_of_visit: ${responseData['Purpose_of_visit']}'; }); } else { throw Exception('Failed to submit'); } } catch (e) { setState(() { result = 'Error: $e'; }); } } And below is the … -
ImportError for django-simple-history in VS Code: "Import 'simple_history.models' could not be resolvedPylance"
I'm currently working on a Django project and want to use django-simple-history to track changes on my models. However, I'm facing an issue with importing the HistoricalRecord model from simple_history.models. Whenever I try to import it in my code, Visual Studio Code underlines the import statement and shows the error message "Import 'simple_history.models' could not be resolvedPylance". Here are the steps I've taken to troubleshoot the issue: I activated my virtual environment where django-simple-history is installed and then using pip freeze, I confirmed that django-simple-history==3.5.0 is listed. I also used pip show django-simple-history to ensure the package details are correct, and it shows the expected information. I deleted the virtual environment and recreated it, but the problem persists. I checked the location where the virtual environment saves the library-specific data (venv\Lib\site-packages\simple_history), and I can see the HistoricalRecords model there. Despite these efforts, I'm still unable to resolve the import error in VS Code. Could anyone suggest what might be causing this issue and how I can fix it? Any help or guidance would be greatly appreciated. Here is the error: (https://i.stack.imgur.com/mzpZQ.png) Thank you! -
Unable to Resolve jQuery ReferenceError: $ is not defined in JavaScript File
I'm encountering an issue with my JavaScript file where I'm getting the error "Uncaught ReferenceError: $ is not defined" in the browser console. I'm using jQuery in my JavaScript code, but it seems like jQuery is not being recognized. Here's the relevant portion of my JavaScript file (address.js): console.log("Hi"); $(document).ready(function(){ $(document).on("click",".make-default-address",function(){ let id = $(this).attr("data-address-id") let this_val = $(this) console.log("Id is:", id); console.log("Element is:", this_val); $.ajax({ url:"/make-default-address", data: { "id":id }, dataType: "json", success: function(response){ console.log("Address Made default....."); if (response.boolean == True){ $(".check").hide() $(".action_btn").show() $(".check"+id).show() $(".button"+id).hide() } } }) }) }) I've ensured that jQuery is loaded before this script in my HTML file: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script src="{% static 'assets/js/address.js' %}"></script> However, I'm still getting the error. Can someone please help me understand what might be causing this issue and how I can resolve it? Any assistance would be greatly appreciated. Thank you! -
Django Channels direct messaging and server sent events
Hello I am building a multiplayer poker game. So far I have built the poker portion where instances of players are created and a table is created then hands are stored in the player object and the board and pot and betting takes place in the table instance. I’d like to create a multiplayer version where instead of taking inputs from the command line, a chat room like interface will take in betting and display hands and the board. Functionality I need: output hand to one specific websocket input bet from one specific websocket and then output that bet to the next websocket and receive a bet and output to the next and so on output pot size and board and player balance to specific websocket So far I have used the channels tutorial to build a basic chat app. The issue I’m facing is that most of the tutorials and content are tailored toward broadcasting messages to everyone. Please help! -
calendar keeps showing the wrong time
I am trying to fix the timezones for the calendar. It sends to the django server the times as an ISO format with the offsets as the timezone that the user selects at the dropdown menu and saves it. It is saved in the server correctly. But upon loading it into the calendar, it seems to interpret it as actually 5 hours ahead (America/Chicago CST time) instead of the time format as 00:00:00 that was input originally. And yes the offset is -5. I've already tried removing the timeZone option in the fullcalendar variable and that didn't do anything. #calendar.html var calendar = $("#calendar").fullCalendar({ // timeZone: $("#id_timezone").val(), timeZone: "UTC", #UTC is just for testing purposes header: { left: "prev,next today", center: "title", right: "month,agendaWeek,agendaDay", }, events: "/all_events", selectable: true, selectHelper: true, editable: true, eventLimit: true, eventDurationEditable: true, select: function (start, end, allDay) { var title = prompt("Enter Event Title"); if (title) { var start = $.fullCalendar.formatDate(start, "Y-MM-DD HH:mm:ss"); var end = $.fullCalendar.formatDate(end, "Y-MM-DD HH:mm:ss"); $.ajax({ type: "GET", url: "/add_event", data: { title: title, start: start, end: end, timezone: $("#id_timezone").val(), }, dataType: "json", success: function (data) { calendar.fullCalendar("refetchEvents"); alert("Added Successfully " + start); }, error: function (data) { alert( "There is … -
Django field isn't being migrated
I have a model, for each object I want a random string on creation activation. I'm currently creating the model like so; from django.db import models from django.contrib.auth.models import User from django.utils.translation import gettext_lazy as _ import string import random def get_random_12_string(): return ''.join(random.choices(string.ascii_uppercase + string.ascii_lowercase + string.digits, k=12)) class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='customer') organization = models.ForeignKey(Organization, on_delete=models.CASCADE, related_name='clients') phone_number = models.CharField(_("Phone Number"), max_length=15) date_of_birth = models.DateField(_("Date of Birth"), blank=True, null=True) # Optional created_at = models.DateTimeField(_("Created At"), auto_now_add=True) updated_at = models.DateTimeField(_("Updated At"), auto_now=True) activation = models.CharField(_("Activation Code"), max_length=14, default=get_random_12_string) def __str__(self): return f'{self.user.first_name} {self.user.last_name}' class Meta: verbose_name = _("Customer") verbose_name_plural = _("Customers") ordering = ['created_at'] # Orders by creation date by default in queries. However after running python manage.py makemigrations & python manage.py migrate (both saying they are succesful). The field doesn't even get created in the database and when going to the admin panel I am getting an error that the field doesn't exist. Migrations for 'portal': portal\migrations\0005_alter_client_activation.py - Alter field activation on client Operations to perform: Apply all migrations: admin, api, auth, contenttypes, cookie_consent, portal, public, sessions, sites Running migrations: Applying portal.0005_alter_client_activation... OK -
ModuleNotFoundError: No module named 'django_DRF'
I just running the django project for welcome, it come out the issue with No module named 'django_DRF'. python==3.8 django==4.2 I have installed the djangorestframework and add rest_framework in INSTALLED_APPS, but i still have the same issue. Thank you for help!! -
Page 404 when Django project WSGIScriptAlias is not /
I am learning Django. I am on Python 3.12.2, Django 5.0.3, Apache HTTPD 2.4.58, Windows 11. I have just done startproject (no startapp yet). Here is my current directory structure: D:\dev\htdocs # Apache HTTPD DocumentRoot ├───... # Other directories │ └───nutrihub_pyvenv # venv container for Django project ├───.venv # I use pipenv │ └───nutrihub │ db.sqlite3 │ manage.py │ Pipfile │ Pipfile.lock │ └───nutrihub asgi.py settings.py urls.py wsgi.py __init__.py Here is my Apache config: WSGIScriptAlias /nhub "d:/dev/htdocs/nutrihub_pyvenv/nutrihub/nutrihub/wsgi.py" WSGIPythonHome "d:/dev/htdocs/nutrihub_pyvenv/.venv" WSGIPythonPath "d:/dev/htdocs/nutrihub_pyvenv/nutrihub;" WSGIApplicationGroup %{GLOBAL} <Directory "d:/dev/htdocs/nutrihub_pyvenv/nutrihub/"> <Files "wsgi.py"> Require all granted </Files> </Directory> I added the following to D\dev\htdocs\nutrihub_pyvenv\nutrihub\nutrihub\settings.py ALLOWED_HOSTS = ['localhost', '127.0.0.1'] When I run the following command: D:\dev\htdocs\nutrihub_pyvenv\nutrihub (.venv) λ py manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. March 26, 2024 - 06:56:13 Django version 5.0.3, using settings 'nutrihub.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. ... I see the page with The install worked successfully! Congratulations! You are seeing this page because DEBUG=True is in … -
Django console giving not found error for api even though its visible in browser
I have a django backend setup. In that I have a few folders, base (app that holds my models), a folder named "api" that has a views.py and urls.py for my apis, and a folder called backend (djangos base folder where settings.py, wsgi.py, etc are). Now, I already have a few APIs in my views.py (in api folder) that are linked and working, and I just tried to create a new one. Although I did the same steps, followed he same linkage, this API is not working when accessed from my frontend, the console says: "Not Found: /api/getmodel/ [25/Mar/2024 22:36:50] "GET /api/getmodel/ HTTP/1.1" 404 3116" When I go to "http://127.0.0.1:8000/api/getmodel/" I'm seeing the default djangorestframework view so I know that the view exists and there is infact something on that link. Here are the relevant files: urls.py (in api folder): from django.urls import path from . import views from rest_framework_simplejwt.views import ( TokenRefreshView, ) from .views import MyTokenObtainPairView urlpatterns = [ path('registeruser/', views.register_user), path('token/', MyTokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('createmodel/', views.create_model), path('getmodel/', views.fetch_model), ] views.py (in api folder): from rest_framework.response import Response from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated from django.contrib.auth.hashers import make_password from base.models import User, HumanModel … -
Make Saleor multitenant
I'm currently working on an E commerce platform like shopify. I found tons of good reviews about saleor open source project , and went for it to speed up the development. The plan i'm going with is to add Multitenancy to SaleOr with Django Tenants package. But I'm pretty new to SaleOr and can't find any proper tutorial about what i'm trying to do. Does anyone here mind helping please ? Reading and following the docs didn't help. Any guidance is appreciated I tried following the docs for installation but it's quite confusing for me. A beginner comprehensive step by step guide or tutorial would be wonderful*. Any form of kind assistance too. -
Connecting Django container to MySQL container in a single AWS ECS Fargate task definition
I have a repository here. I am currently struggling with deploying it to AWS ECS. The repository is configured to use Github Actions to build the two containers and then ship them to ECR, then update an ECS task definition to pull the most recent image commit. Both containers startup, but then they fail. The Django container gives an error saying django.db.utils.OperationalError: (2005, "Unknown server host 'template-db' (-2)") From what I understand, the name of the DB_HOST in the settings.py should be the name of the container when they are in the same task definition. Why does it not work then? Is there some fundamental networking concept here I don't understand? I am using ECS Fargate, and am therefore on awsvpc for the network mode. I also tried changing the hostname to localhost, as that worked in the podman-compose setup on local, which didn't work. I'm not surprised, since these are separate containers in a serverless environment. What I've tried should be visible at the repository here: -
[[Errno 2]] No such file or directory: '/tmp/tmp1d93dhp7.upload.mp4' in Django
I've been moving development of my website over to using Docker. I recently adjusted the location of media files when I was presented with this error: [Errno 2] No such file or directory: '/tmp/tmp1d93dhp7.upload.mp4' in Django. So far I've checked for typos in my file location code in my settings, views and models. The website works by simply storing user uploaded media files in a media folder. Uploaded files are stored in media/human. Here is the relevant code: views.py: ... fs = FileSystemStorage() filename = fs.save(uploaded_file.name, uploaded_file) uploaded_file_path = fs.path(filename) file_type = mimetypes.guess_type(uploaded_file_path) request.session['uploaded_file_path'] = uploaded_file_path user_doc, created = RequirementsChat.objects.get_or_create(id=user_id) files = request.FILES.getlist('file') for file in files: user_doc, created = RequirementsChat.objects.get_or_create(id=user_id) uploaded_file = UploadedFile(input_file=file, requirements_chat=user_doc, chat_id = user_id) uploaded_file.save() user_doc.save() ... The error seems to be caused by the uploaded_file.save() line. models.py: class RequirementsChat(models.Model): id = models.CharField(primary_key=True, max_length=40) alias = models.CharField(max_length=20, blank=True, null=True) email = models.CharField(max_length=100, blank=True, null=True) language = models.CharField(max_length=10, blank=True, null=True) due_date = models.CharField(max_length=10, blank=True, null=True) subtitle_type = models.CharField(max_length=10, blank=True, null=True) transcript_file_type = models.CharField(max_length=10, blank=True, null=True) additional_requirements = models.TextField(max_length=500, blank=True, null=True) date = models.DateTimeField(auto_now_add=True, blank=True, null=True) url = models.CharField(max_length=250, blank=True, null=True) task_completed = models.BooleanField(default=False) class UploadedFile(models.Model): input_file = models.FileField(upload_to='human_upload/')#new chat_id = models.CharField(max_length=40, null= True) requirements_chat = models.ForeignKey(RequirementsChat, on_delete=models.CASCADE, … -
Django Getting a List of Items from one Model and using it to filter another
So, I have 3 tables in my model, house, room, and item. room contains a foreign key to house, and item contains a foreign key to room. I want to be able to query by the house and get all the items in the house. class room(models.Model): house= models.ForeignKey(house, on_delete=models.CASCADE, null=False) name = models.CharField(max_length=60, null=False) def __str__(self): return self.name class house (models.Model): name = models.CharField(max_length=50, unique=True, null=False) #House name, unique houseCode = models.CharField(max_length=5, null=False) # house code class item(models.Model): room= models.ForeignKey(room, on_delete=models.CASCADE, null=False) # ForeignKey to room itemName = models.CharField(max_length=255, null=False) # item So I want to be able to pass in a house ID and get all the associated items in the house, grouped by rooms, so the desired return would be something like. { room:living room, items:[couch, tv] room: bedroom, items:[bed, nightstand] } Not sure what I need in the new serializer/view to be able to do this as all my current serializers/views are just the model and all fields for basic CRUD operations. -
How to change a queryset in Django?
I try to change output of Django serializer. Class-based view has function get_projects that returns queryset of Contract instances. Relationship of Contract and Project is one-to-many: class Contract(models.Model): project = models.ForeignKey(Project) Now MySerializer's response is: [ { "projectGuid": "project_guid_1", "projectName": "project_name_1", "contractGuid": "contract_guid_1", "contractNumber": "contract_number_1" }, { "projectGuid": "project_guid_1", "projectName": "project_name_1", "contractGuid": "contract_guid_2", "contractNumber": "contract_number_2" }, { "projectGuid": "project_guid_2", "projectName": "project_name_2", "contractGuid": "contract_guid_4", "contractNumber": "contract_number_4" }, { "projectGuid": "project_guid_2", "projectName": "project_name_2", "contractGuid": "contract_guid_5", "contractNumber": "contract_number_5" }, ] I would like to change serializer output into such structure: [ { "project_guid": "project_guid_1", "project_name": "project_name_1", "contracts": [ { "contract_guid": "contract_guid_1", "contract_number": "contract_number_1", }, { "contract_guid": "contract_guid_2", "contract_number": "contract_number_2", }, .... ] }, { "project_guid": "project_guid_2", "project_name": "project_name_2", "contracts": [ { "contract_guid": "contract_guid_4", "contract_number": "contract_number_4", }, { "contract_guid": "contract_guid_5", "contract_number": "contract_number_5", }, .... ] }, ] How can I do this? -
Getting DisallowedRedirect error with password changin view - Django
views.py @login_required def mudar_senha(request): if request.method == 'POST': print(request) form = PasswordChangeForm(user=request.user, data=request.POST) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) # Importante para não deslogar o usuário após a mudança de senha return HttpResponseRedirect(reverse('users:perfil')) else: form = PasswordChangeForm(user=request.user) return render(request, 'users/editar_usuario.html', {'form': form}) urls.py """Define padrões de URL para users""" from django.contrib.auth.views import LoginView, LogoutView, PasswordChangeView from django.urls import path # Importa o modúlo viws para a pasta do app "." from . import views app_name = "users" urlpatterns = [ path('login/' , LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', LogoutView.as_view(next_page='learningLogApp:index'), name='logout'), path('perfil/', views.perfil, name='perfil'), path('registrar/', views.registrar, name='registrar'), path('editar/', views.editar_usuario, name='editar_usuario'), path('mudar_senha/', PasswordChangeView.as_view(success_url='learningLogApp:index'), name='mudar_senha'), ] **Exception Type: **DisallowedRedirect try this: return HttpResponseRedirect(reverse('users:perfil')) and this: sucess_url = reverse_lazy(request, 'users/perfil.html') and this: return reverse_lazy(request, 'users/perfil.html') and this: return reverse_lazy(request, 'users:perfil') and this: return reverse_lazy('users:perfil') and this: return redirect('users:perfil') and this: return HttpResponseRedirect(reverse('learningLogApp:index')) and this: return redirect('users:perfil') Same error in all cases. Ps. The password ARE changing. The problem is with the redirect! (Exception Value: Unsafe redirect to URL with protocol) -
How can I make a paragraph in Django Admin form to be italic? I am using Vue3 Composition API for frontend?
I am building a blog app with a body TextField in Django Admin with Vue3 composition API as frontend. I have tried several ways to make the body (article) to be italic but It only displays the raw input (e.g. italic). I want to make a paragraph italic in Django Admin with body textfield. How do I do that? Admin.py: from django.contrib import admin from blog.models import Profile, Post, Tag from django import forms from .widget import ItalicizedTextInput class PostModelAdminForm(forms.ModelForm): body = forms.CharField(widget=ItalicizedTextInput) class Meta: model = Post fields = '__all__' @admin.register(Profile) class ProfileAdmin(admin.ModelAdmin): model = Profile @admin.register(Tag) class TagAdmin(admin.ModelAdmin): model = Tag @admin.register(Post) class PostAdmin(admin.ModelAdmin): model = Post form = PostModelAdminForm list_display = ( "id", "title", "subtitle", "slug", "publish_date", "published", "body" ) list_filter = ( "published", "publish_date", ) list_editable = ( "title", "subtitle", "slug", "publish_date", "published", "body", ) search_fields = ( "title", "subtitle", "slug", "body", ) prepopulated_fields = { "slug": ( "title", "subtitle", ) } date_hierarchy = "publish_date" save_on_top = True @admin.register(Tag) class TagAdmin(admin.ModelAdmin): model = Tag @admin.register(Post) class PostAdmin(admin.ModelAdmin): model = Post form = PostModelAdminForm list_display = ( "id", "title", "subtitle", "slug", "publish_date", "published", "body" ) list_filter = ( "published", "publish_date", ) list_editable = ( "title", "subtitle", "slug", … -
How do I start properly Django project?
I wrote C:\Users\jj>django-admin startproject mysite And the results are Fatal error in launcher: Unable to create process using '"c:\program files\python38\python.exe" "C:\Program Files\Python38\Scripts\django-admin.exe" startproject mysite' I tried to start my first django project, but It wont open. I can't find any solutions to this problem on the internet and I have not idea what to do next -
DB PostgreSQL data invisible in my website
we developing a website and I have a problem with data stored in DB PostgreSQL locally including images uploaded in some pages from DB just visible to me when I share the code with my team they can't see the images even though they have already been uploaded to their directory file in the project how can I fix that and there are steps we should take when we making a website and using DB ( we use the same usename;and pass of DB server and when i update the database and they pull the code it just update the schema without the data i stored -we use vs code ide,python lang and Django framework,PostgreSQL DB Github for sharing) -
Github mistakes. I lost latestfile
Github mistake I didnot know what i did. but i just deleted all my files . a day before i commit directly to main. i now create a branch , commit , goto main and then merge branch to main and push. i accidentally deleted all my latest work. then i am with old data. it only shows one commit in git log of lastnight which was my first commit of project. *jobsearch is project name add job and notification was commit message dbc0f6f (HEAD -> main, origin/main) HEAD@{0}: checkout: moving from branch1 to main cd95d6d (branch1) HEAD@{1}: commit: add job and notification dbc0f6f (HEAD -> main, origin/main) HEAD@{2}: checkout: moving from main to branch1 dbc0f6f (HEAD -> main, origin/main) HEAD@{3}: checkout: moving from main to main dbc0f6f (HEAD -> main, origin/main) HEAD@{4}: commit (initial): jobsearch PS C:\Users\gunar\OneDrive\Desktop\Coders\JobSearch> git reset --hard HEAD~ undo cd95d6d (branch1) HEAD@{1}: commit: add job and notification dbc0f6f (HEAD -> main, origin/main) HEAD@{2}: checkout: moving from main to branch1 dbc0f6f (HEAD -> main, origin/main) HEAD@{3}: checkout: moving from main to main dbc0f6f (HEAD -> main, origin/main) HEAD@{4}: commit (initial): jobsearch A day before i commit directly to main. i now create a branch , commit , … -
Django 403 "detail": "Authentication credentials were not provided." Knox Tokens
I was following this tutorial (https://github.com/bradtraversy/lead_manager_react_django/tree/db45e4f6fc05a3481e7b8a0223e0aab0355a84b6) to make a Django-React-Redux application. I am having trouble with my UserAPI, specifically when making a GET request. Note that I am using knox tokens. As the logout function works fine (this function is a default from knox), I can see that the token is properly generated from the login, as I use this token for logout. I suspect that there is something in my settings.py that is wrong. The error is: 403: "detail": "Authentication credentials were not provided." class UserAPI(generics.RetrieveAPIView): # this route needs protection # need a valid token to view permission_classes = [ permissions.IsAuthenticated, ] serializer_class = UserSerializer def get_object(self): return self.request.user # Get the registered organizations of the user @action(methods=['get'],detail=True) def registered_orgs(self,request,*args,**kwargs): instance = self.get_object() orgs = instance.followed_organizations.all() serializer = OrganizationSerializer(orgs,many=True) return Response(serializer.data) Here is my settings file: """ Generated by 'django-admin startproject' using Django 4.1.1. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.1/ref/settings/ """ from pathlib import Path import os import mimetypes mimetypes.add_type("text/javascript", ".js", True) # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # … -
how can i fix the ImportError cannot import name 'get_accounts'
hi im trying out python and django for the first time and im trying to set up a simple route to display some data. The issue im running into is that when i try to run the webserver i keep getting this importError regarding one of the functions in my views.py file located in the accounts folder. any help would be greatly appreciated!!! django version: 5.0.3 python version: 3.11.8 Error - ImportError: cannot import name 'get_accounts' from 'accounts.views' /accounts/views.py from django.http import JsonResponse from .models import Account def get_accounts(): accounts = Account.objects.all() data = [{"id": account.id, "type": account.type, "balance": account.balance,"transactions": account.transactions} for account in accounts] return JsonResponse(data, safe=False) /accounts/urls.py from django.urls import path from . import views app_name = "accounts" urlpatterns = [ path('accounts_list/', views.get_accounts, name='account-list'), ] urls.py from django.urls import path from accounts.views import get_accounts urlpatterns = [ path('api/accounts/', get_accounts), ] -
Why nginx don't see staticfiles and Media files Django +nextjs +Docker
I have Nginx config and using Docker to server Django, Nextjs and Nginx server { listen 80 default_server; return 403; } server { listen 80; location /staticfiles/ { alias /app/staticfiles/; } location /mediafiles/ { alias /app/mediafiles/; } location / { proxy_pass http://nextjs:3000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } location ~* ^/(api|admin) { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_pass http://server:9000; } } The problem is when I added a location to nextjs, nginx doesn't want to see static files, but if I use config without next js django + admin it serves ok. server { listen 80; location / { try_files $uri @proxy_django; } location @proxy_django { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_pass http://server:9000; } location /staticfiles/ { alias /app/staticfiles/; } location /mediafiles/ { alias /app/mediafiles/; } } Thanks for helping