Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use node modules within a Django app
I developed a web map app using Django. I used Leaflet for the map and I'd like to add some Leaflet plugins that are meant to be installed using npm. I'm new to node (I've only used it in Development during my classes) and have never used it in Production or with Django. I'm wondering if I have to configure anything else in my project or if I can just npm init and then npm install anything. I suppose I'd have to add node_modules to my .gitignore but I'm not sure how should I manage the static files generated by node and how should I import modules into my django templates. I'd be using Node only for front-end stuff, all my back-end is managed by Django. I haven't installed anything yet as I'm afraid I'll break my web. -
How can put my python django project on live?
I have create a project by python django this project work as an documents Archive by uploding the doucments by the admin panle. The problem is that: 1- I want to deploy on my company server. can anyone tell me how to do it because when I have tried the 'python manage.py runsever ipaddressofservermachine, it is working on server machine but it is not working in other laptops. i thought it should have worked but it did not. 2- I want the uploaded file storage not in my :D drive i wanted to be stored in company server I have tried many ways and search in youtube i did not find the way to deploy my project live and make it live and accessible for my employes and make the uploaded file storage not in my :D drive i wanted to be stored in company server -
Remove URL prefix in Jinja + Django
In Django model URLs stored in URL field, so the values are look like "https://example.com/id" In HTML rending with Jinja code should be without https:// prefix like this Can't find any embedded Jinja filters or elegant solution how to remove prefix on the fly without extra coding in DB -
Django view doesn’t recognize the parameter name from template
I am trying to pass two parameters from template (“zn” and “ru”) to filter posts in view. It seems to me, that the variables of both parameters are OK, but not under proper name. The view probably doesn’t recognize which is which. Filtering with parameter “zn” works, but filtering with parameter “ru” doesn’t (see the error statement in picture). enter image description here urls.py: from django.urls import path from . import views urlpatterns = [ ... path("clanky/", views.clanek_vyber, name="clanky_vyber", kwargs={'zn': '', 'ru': ''}), path("clanky/<slug:zn>/", views.clanek_vyber, name="clanky_vyber", kwargs={'ru': ''}), path("clanky/<slug:ru>/", views.clanek_vyber, name="clanky_vyber", kwargs={'zn': ''}), path("clanky/<slug:zn>/<slug:ru>/", views.clanek_vyber, name="clanky_vyber"), views.py: from django.shortcuts import render from django.utils import timezone from django.views import generic from django.core.paginator import Paginator ... from .models import Clanek, Rubrika, Znacka, GalerieObrazku, Hlavni_banner ... def clanek_vyber(request, zn, ru): bannery_1 = Hlavni_banner.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')[:1] clanek_znacka = Clanek.objects.values('znacka') znac = Znacka.objects.filter(id__in=clanek_znacka) rubr = Clanek.objects.distinct('rubrika').order_by('rubrika_id') if (zn!="" and ru!=""): uvodni_clanek = Clanek.objects.filter(znacka__slug=zn).filter(rubrika__slug=ru).order_by('-published_date')[:1] zna = Znacka.objects.get(slug=zn) rub = Rubrika.objects.get(slug=ru) cla_vyb = Clanek.objects.filter(znacka__slug=zn).filter(rubrika__slug=ru).order_by('-published_date')[1:] paginator = Paginator(cla_vyb, 20) # ukáže dvacet dalších článků page_number = request.GET.get("page") page_obj = paginator.get_page(page_number) context = { 'bannery_1': bannery_1, 'uvodni_clanek': uvodni_clanek, 'page_obj': page_obj, 'znac': znac, 'zna': zna, 'zn': zn, 'rubr': rubr, 'rub': rub, 'ru': ru } return render(request, "zentour/clanky.html", context) if(zn!=""): uvodni_clanek = Clanek.objects.filter(znacka__slug=zn).order_by('-published_date')[:1] … -
Why am I getting DoesNotExist for the parent model in save_related
I am firing a celery task in save_related that takes the parent object id and does a get query to obtain the instance for use. Problem is some of the get queries are failing with DoesNotExist. This doesn't make sense to me because the Django docs clearly state that "Note that at this point the parent object and its form have already been saved.". Also why are others not failing? I am about to experiment with what happens when I call super().save_related(...) before the celery task but I don't think that should be an issue because of the note above. Django==4.2.3 -
mock a shell script in Django/DRF test
I tried to make some test on a method in views, but this method call a script shell, this script is write to work in another OS so I need to mocke this. here the test: @patch('check_web_share_file_folder.get_path_from_inode') def test_list_with_search_mocked(self, mock_get_attribute): mock_get_attribute.return_value = 'expected value' request = self.factory.get('/fake-url') force_authenticate(request, user=self.user) view = WebShareFileFolderViewSet.as_view({'get': 'list'}) response = view(request) self.assertEqual(response.status_code, status.HTTP_200_OK) here the problem, I encounter this error with the test: AttributeError: <function check_web_share_file_folder at 0x00000237FD567708> does not have the attribute 'get_path_from_inode' check_web_share_file_folder.py have of course get_path_from_inode() def get_path_from_inode(inode): std, err, code = popen_wrapper([ 'sudo', 'get_path_from_inode.sh', str(inode) ]) if code != 0: return False return str(std.strip())[1:] -
unique_together in bulk_create
this is my model: class Reminder(models.Model): timestamp = models.DateTimeField() time_frame = models.CharField(default = "5minutes" , max_length=30,choices=[ ("5minutes","5minutes"), ("15minutes","15minutes"), ("30minutes","30minutes"), ("1hour","1hour"), ("4hours","4hours"), ("1day","1day") ]) coin = models.ForeignKey(Coin,on_delete=models.CASCADE) class Meta: unique_together = ["coin","time_frame"] i want to use bulk_create command for create a lot of object from this model. options of bulk_create is update_fields and unique_fields. but i have unique_together fields. what i suppose to do for this code: Reminder.objects.bulk_create(reminders, update_conflicts=True,update_fields=['timestamp'],batch_size=1000) -
Connecting a Django project that is hosted on a Virtual Machine with Nginx and Gunicorn
I'm new to deploying applications. Currently, I'm hosting my Django project on an Ubuntu virtual machine with IP address 192.168.xxx.xxx. It is hosted on a physical service with public IP address of 202.xxx.xxx.xxx (using port 8080). I have gunicorn and nginx installed and incorporated, and they're running properly as sudo systemctl status gunicorn and sudo systemctl status nginx show that they're running with no errors. However, when I try to access the public IP address 202.xxx.xxx.xxx:8080, I'm getting the default Nginx page. As for how I setup my gunicorn and nginx, I followed the guide posted here: https://medium.com/@muhammadali_12976/deploying-django-on-a-local-virtual-machine-virtualbox-with-nginx-and-gunicorn-369f70937913 Here's the gunicorn.socket file: [Unit] Description=gunicorn socket [Socket] ListenStream=/home/myProject/myProject.sock [Install] WantedBy=sockets.target Here's the gunicorn.service file: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=myUserName Group=www-data WorkingDirectory=/home/myProject ExecStart=/home/myProject/env/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/myProject/myProject.sock core.wsgi:application [Install] WantedBy=multi-user.target Here's the contents of my /etc/nginx/sites-available/myProject file server { listen 80; server_name 192.168.xxx.xxx; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/myProject; } location / { include proxy_params; proxy_pass http://unix:/home/myProject/myProject.sock; } } Should I have used the public address in server_name or the IP address of the virtual machine where my Django project is hosted? In addition, I also tried changing the port … -
I am getting broken image in a html(cart) page
I am creating an add-to-cart function for my website. I am getting broken images in my cart.html page. So, In cart.html: {% for product_id, item in data.items %} <div class="col-md-12 col-lg-8"> <div class="items"> <div class="product"> <div class="row"> <div class="col-md-3"> <img class="img-fluid mx-auto d-block image" src="{{item.image}}" > <!-- #1 --> </div> <div class="col-md-8"> <div class="info"> <div class="row"> <div class="col-md-5 product-name"> <div class="product-name"> <a href="#">{{item.title}}</a> <div class="product-info"> <div>Display: <span class="value">5 inch</span></div> <div>RAM: <span class="value">4GB</span></div> <div>Memory: <span class="value">32GB</span></div> </div> </div> </div> <div class="col-md-4 quantity"> <label for="quantity">Quantity:</label> <input id="quantity" type="number" value ="1" class="form-control quantity-input"> </div> <div class="col-md-3 price"> <span>{{item.price}}</span> </div> </div> </div> </div> </div> </div> </div> </div> You can see in the #1 that I add the image there. I also created view for add-to-cart function So, in views.py: def add_to_cart(request): cart_product={} cart_product[str(request.GET['id'])]={ 'title': request.GET['title'], 'qty': request.GET['qty'], 'price': request.GET['price'], 'image': request.GET['image'], 'pid': request.GET['pid'], } if 'cart_data_obj' in request.session: if str(request.GET['id']) in request.session['cart_data_obj']: cart_data= request.session['cart_data_obj'] cart_data[str(request.GET['id'])]['qty']=int(cart_product[str(request.GET['id'])]['qty']) cart_data.update(cart_data) request.session['cart_data_obj']=cart_data else: cart_data=request.session['cart_data_obj'] cart_data.update(cart_product) request.session['cart_data_obj']=cart_data request.session['total_cart_items'] = len(cart_data) else: request.session['cart_data_obj']=cart_product request.session['total_cart_items'] = len(cart_product) return JsonResponse({"data":request.session['cart_data_obj'],'totalcartitems': request.session['total_cart_items']}) In the function.js: $("#add-to-cart-btn").on("click",function(){ let quantity=$("#product-quantity").val() let product_title=$(".product-title").val() let product_id=$(".product-id").val() let product_price = $("#current-product-price").text() let product_image = $(".product-image").val() let product_pid=$(".product-pid").val() let this_val=$(this) console.log("Quantity:", quantity); console.log("Id:", product_id); console.log("PId:", product_pid); console.log("Image:", product_image); console.log("Title:", product_title); … -
Django 5 postgres superuser login fail
I created a Django project SQLite. I decided to move from SQLite to PostgreSQL. All migrations worked. I created the superuser successfully but when I try logging in the admin it says that the user can't be found. this is the users model from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class CustomUser(AbstractUser): """ Class for creating custom users. There are 3 user types in this class """ USER_TYPE_CHOICES = ( ('manager', 'Manager'), ('supervisor', 'Supervisor'), ('employee', 'Employee'), ) user_type = models.CharField(max_length=20, choices=USER_TYPE_CHOICES) is_active = models.BooleanField(default=False) name = models.CharField(max_length=255) email = models.EmailField(unique=True) national_id = models.CharField(max_length=20, unique=True) def __str__(self): return self.email # Provide a unique username or remove the unique constraint from email def save(self, *args, **kwargs): if not self.username: self.username = self.name # Use email as username or provide a unique username super().save(*args, **kwargs) I tried logging in the admin. It says the user is not found. I used both email and username to be sure but the user still can't be found. This is pip freeze: pip freeze asgiref==3.7.2 attrs==23.1.0 bcrypt==4.1.2 Django==5.0 django-cors-headers==4.3.1 django-filter==23.5 djangorestframework==3.14.0 djangorestframework-simplejwt==5.3.1 drf-spectacular==0.27.0 Faker==21.0.0 inflection==0.5.1 jsonschema==4.20.0 jsonschema-specifications==2023.11.2 Markdown==3.5.1 mysqlclient==2.2.3 psycopg2==2.9.9 PyJWT==2.8.0 python-dateutil==2.8.2 pytz==2023.3.post1 PyYAML==6.0.1 referencing==0.32.0 rpds-py==0.15.2 six==1.16.0 sqlparse==0.4.4 typing_extensions==4.9.0 uritemplate==4.1.1 -
Export file automatic download not working in Django
I have trouble when exporting excel file through export button it does not appear download automatically, but when I inspect element then selecting network if I clicked export status it will download, but for me it will hassle to inspect element instead just click one button. I used Chrome I already tried set to automatic download but the result will the same, Is this the issue for the new version of the web browser or in my code? This is my code @csrf_exempt def export_status(request): with connection.cursor() as cursor: cursor.execute(""" SELECT tev_incoming.id,tev_outgoing.dv_no AS dv_no, tev_incoming.code, tev_incoming.account_no, tev_incoming.id_no, tev_incoming.first_name, tev_incoming.middle_name, tev_incoming.last_name, tev_incoming.date_travel, tev_incoming.division, tev_incoming.section, tev_incoming.status_id, au.first_name AS incoming_by,rb.first_name AS reviewed_by, tev_incoming.original_amount, tev_incoming.final_amount, tev_incoming.incoming_in AS date_actual, tev_incoming.updated_at AS date_entry, tev_incoming.incoming_out AS date_reviewed_forwarded, tev_bridge.purpose AS purposes FROM tev_incoming INNER JOIN ( SELECT MAX(id) AS max_id FROM tev_incoming GROUP BY code ) AS latest_ids ON tev_incoming.id = latest_ids.max_id LEFT JOIN tev_bridge ON tev_incoming.id = tev_bridge.tev_incoming_id LEFT JOIN tev_outgoing ON tev_bridge.tev_outgoing_id = tev_outgoing.id LEFT JOIN auth_user AS au ON au.id = tev_incoming.user_id LEFT JOIN auth_user AS rb ON rb.id = tev_incoming.reviewed_by ORDER BY tev_incoming.id DESC; """) rows = cursor.fetchall() response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename={date}-TRIS-REPORT.xlsx'.format( date=datetime.now().strftime('%Y-%m-%d'), ) workbook = Workbook() worksheet = workbook.active worksheet.title … -
Django hosting in cpanel with out using Setup Python App
I want to host my Django project in cPanel with out using Setup Python App. How can i do that? Please provide step by step solution from beginning. I search for the solution in google, but i can't get the answer. Please help me. -
Django admin : How to show a model as inline inside another model, which is indirectly related
I have models named user, authtoken and userdevice. class User(LifecycleModelMixin, AbstractUser): email = models.EmailField(unique=True) slug = models.SlugField(max_length=100, unique=True, blank=False, null=True) class AuthToken(models.Model): objects = AuthTokenManager() digest = models.CharField( max_length=CONSTANTS.DIGEST_LENGTH, primary_key=True) token_key = models.CharField( max_length=CONSTANTS.TOKEN_KEY_LENGTH, db_index=True) user = models.ForeignKey(User, null=False, blank=False, related_name='auth_token_set', on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) expiry = models.DateTimeField(null=True, blank=True) class UserDevice(models.Model): token = models.OneToOneField(AuthToken, on_delete=models.CASCADE, related_name="auth_token") device_type = models.CharField(max_length=100, choices=DevicesChoices.choices) access_type = models.CharField(max_length=100, choices=AccessChoices.choices) device_brand = models.CharField(max_length=100, null=True, blank=True) I need to show the userdevice inside the user detail page in admin panel as inline. Django Error admin.E202 'userdevice' has no ForeignKey to 'accounts.user' Getting this error. Any help will be much appreciated. -
MySQL/Django/Docker -> 1045, "1045 (28000): Access denied for user 'X'@'xx.xxx.xx.xx' (using password: YES)", '28000'
I have mariadb/mysql and django running as separate docker containers (both have separate docker-compose.yml files as well). When I try to build my django docker container using docker-compose build(I have a Dockerfile defined for this with makemigrations and migrate commands in it) my container builds fine and correctly and python manage.py makemigrations and python manage.py migrate work fine as well. However when I do docker exec -ti <django-container-name> bash and try to run python manage.py makemigrations and python manage.py migrate, it doesn't work. I get a 1045, "1045 (28000): Access denied for user '<user>'@'<host>' (using password: YES)", '28000'error. Similarly, when I try to do mysql -h <hostname> -P <port> -u <username> -p I get a bash error saying that mysql doesn't exist (I also get this same error when i do just mysql). Accessing MariaDB: When I do docker exec -ti <mariadb-container-name> bash and run the mysql command, I am able to see the migrations from the initial django build but nothing else after that. Where am I going wrong that django can build and do makemigrations/migrate fine but won't run these commands inside the docker container once it is up and running? I should clarify that mariadb/mysql and django … -
React Router version issue [duplicate]
I just had a quick question about a React project I'm working on. I'm trying to get React Router to route to both a login page and, upon successfully doing that, have it re-route to my app's homepage. However, I'm using version 6, and I keep getting the following error when I try to run it: "[PrivateRoute] is not a component. All component children of must be a or <React.Fragment>" Any insight into how I can reformat my code? Thanks!! import React from 'react'; import { BrowserRouter as Router, Route, Routes, Navigate } from 'react-router-dom'; import Login from './Login'; import Spreadsheetester from './Spreadsheet'; const PrivateRoute = ({ element: Element, ...rest}) => ( <Route {...rest} element={ localStorage.getItem('token') ? ( <Element /> ) : ( <Navigate to="/login" replace /> ) } /> ); const App = () => { return ( <Router> <Routes> <Route exact path="/login" element={<Login />} /> <PrivateRoute exact path="/" element={<Spreadsheet />} /> </Routes> </Router> ); }; export default App; -
Wagtail and Elasticsearch , Lookup "icontains"" not recognised
I'm trying to run a search with Wagtail (5.2) and Elastic (7) When I make a search for Users wagtail_admin/users/?q=ffff I got such error FilterFieldError Cannot filter search results with field "email". Please add index.FilterField('email') to User.search_fields Then I add extra field to search fields in the code class User: search_fields = [ index.SearchField("name", partial_match=True), index.FilterField("email", partial_match=True), ] But just got another error FilterError /wagtail_admin/users/ Could not apply filter on search results: "email__icontains = ffff". Lookup "icontains"" not recognised. How it can be fixed? -
axios response.data is empty when django returns a queryset with a single element
I am using axios to get some data from my backend API made with django. Something very very wired is happening and I have been debugging this for hours. This is the axios function that gets the data: function useGetProducts(category: string, subcategory: string, code:string){ const [products, setProducts] = useState<Product[]>([]); useEffect(() => { axios.get(getQueryUrl(category, subcategory, code)) .then(response => { console.log(response) setProducts(response.data); }) .catch(error => { console.error(error); }); },[]); return products; } And here is my ProductView in django class ProductView(viewsets.ModelViewSet): serializer_class = ProductSerializer def get_queryset(self): queryset = Product.objects.all() cat = self.request.query_params.get('category', None) subcat = self.request.query_params.get('subcategory', None) code = self.request.query_params.get('code', None) if cat and subcat and code: # Sanitize the name parameter using Django's ORM queryset = queryset.filter(code__exact=code) elif cat and subcat: queryset = queryset.filter(category__exact=cat, sub_category__exact=subcat) elif cat: queryset = queryset.filter(category__exact=cat) print(queryset) return queryset Now the thing is when the queryset contains only one element the response.data is an empty array but when the queryset contains more than one element the response.data contains the right amount of elements. The method getQueryUrl works correctly. I tried to limit the output of other querysets that supposed to contain more than 1 element to 1 and same thing, empty array on the frontend side. ChatGPT … -
Django linebreaks disallow CSS Style
I have a problem in my new Django project. In fact, I've created a Model named "Tutorial" which has a Description being a TextField(). So when I call it in my HTML file from my View it works correctly for all except for this one because I need to add linebreaks if I want to keep all the body of my description. And without these linebreaks my CSS works correctly but the text goes through the content area and with linebreaks I show all the text but the CSS style is disallowed, please help me.Linebreaks code (Don't take care about striptags). Here it's without the linebreaksAnd here with linebreaks it's horrible lol Need help please I hope you can help me cause I didn't find anything anywhere. -
Cannot get nested serializers to show related data using Django REST framework
For some reason my nested serializers are not displaying related data. I've searched online for an answer but cannot find any answers that fixes this issue. The demo apps I make using nested serializers work as expected, but on my main app the nested serializers do not display related data. Below is my relevant code. ##models ... class Location(models.Model): user = models.ForeignKey(User, null=False, on_delete=models.CASCADE) name = models.CharField("Full name", max_length=100,) geolocation = models.PointField() address1 = models.CharField("Address line 1", max_length=1024,) address2 = models.CharField("Address line 2", null=True, max_length=1024,) city = models.CharField("City", max_length=50,) STATES = [ ("AL", "Alabama"), ("AK", "Alaska"), ("AZ", "Arizona"), ("AR", "Arkansas"), ("CA", "California"), ("CO", "Colorado"), ("CT", "Connecticut"), ("DE", "Delaware"), ("FL", "Florida"), ("GA", "Georgia"), ("HI", "Hawaii"), ("ID", "Idaho"), ("IL", "Illinois"), ("IN", "Indiana"), ("IA", "Iowa"), ("KS", "Kansas"), ("KY", "Kentucky"), ("LA", "Louisiana"), ("ME", "Maine"), ("MD", "Maryland"), ("MA", "Massachusetts"), ("MI", "Michigan"), ("MN", "Minnesota"), ("MS", "Mississippi"), ("MO", "Missouri"), ("MT", "Montana"), ("NE", "Nebraska"), ("NV", "Nevada"), ("NH", "New Hampshire"), ("NJ", "New Jersey"), ("NM", "New Mexico"), ("NY", "New York"), ("NC", "North Carolina"), ("ND", "North Dakota"), ("OH", "Ohio"), ("OK", "Oklahoma"), ("OR", "Oregon"), ("PA", "Pennsylvania"), ("RI", "Rhode Island"), ("SC", "South Carolina"), ("SD", "South Dakota"), ("TN", "Tennessee"), ("TX", "Texas"), ("UT", "Utah"), ("VT", "Vermont"), ("VA", "Virginia"), ("WA", "Washington"), ("WV", "West Virginia"), ("WI", "Wisconsin"), … -
Django Related Object Reference in Template
Unable to display related object reference set via foreign key relationship in HTML template. Here's the code so far. models.py: class MprVw(models.Model): payloadid = models.TextField(db_column='payLoadID', blank=True, null=True) file = models.TextField(db_column='File', primary_key=True) class Meta: managed = False db_table = 'MPR_VW' class MprWi(models.Model): id = models.TextField(db_column='id', primary_key=True) payloadid = models.TextField(db_column='payLoadID', blank=True, null=True) file = models.ForeignKey(MprVw, on_delete=models.DO_NOTHING, db_column='File') class Meta: managed = False db_table = 'MPR_WI' views.py: def MPR(request): myDls = request.GET.get("dls") myMPR = MprVw.objects.filter(dls=myDls) myMprWi = MprWi.objects.all().values() context = { 'myMPR': myMPR, 'myMprWi': myMprWi, 'myDls': myDls, } MPR = loader.get_template('MPR.html') return HttpResponse(MPR.render(context, request)) HTML: {% for rowmyMPR in myMPR.mprwi_set.all %} <tr> <td>{{ rowmyMPR.file }} {{ rowmyMPR.id }} </td> </tr> {% endfor %} I am expecting to display row data from myMprWi that are the child records of the myMPR parent file. There is currently nothing displaying. -
What is messing with the logging in AsyncWebsocketConsumer?
I have a Django project that's using Channels for websocket communication and I've stumbled upon what I think might be a bug, but I'm not certain so I'm hoping someone that understands this better than I do can help explain what's happening here: Test error message: AssertionError: "INFO:websocket.camera_consumer:Doesn't work" not found in ['INFO:websocket.camera_consumer:Works'] Test that's failing: class TestCameraConsumerTests(TransactionTestCase): async def test_fails(self): communicator = WebsocketCommunicator(TestConsumer.as_asgi(), '/ws/device') with self.assertLogs(f'websocket.camera_consumer', level=logging.INFO) as logs: await communicator.connect(timeout=10) await communicator.disconnect() self.assertIn(f"INFO:websocket.camera_consumer:Doesn't work", logs.output) websocket.camera_consumer.py: import logging from channels.generic.websocket import AsyncWebsocketConsumer def sync_function(): pass class TestConsumer(AsyncWebsocketConsumer): async def connect(self): await super().connect() logger = logging.getLogger(__name__) logger.info("Works") await sync_to_async(sync_function)() logger.info("Doesn't work") What I've learned so far: Moving the getLogger call outside the connect function doesn't fix it Moving the super call below the sync_to_async call does fix it Removing the sync_to_async function (and making sync_function async) also fixes it Somewhere along the way in the sync_to_async function call, the logger handler object that the assertLogs injects gets removed so the first log message gets routed to the test, but the second log message does not I've attempted to step-though the sync_to_async call, however I can't figure out how to monitor the logger object while inside the async loop (I'm … -
Django language switcher is not persistent
Hello I'm struggling with my language switcher. settings.py: LANGUAGE_CODE = 'en' LANGUAGES = [ ('de','Deutsch'), ('en','English') ] urls.py: path('setlang', views.setlang, name='setlang'), index.html: <a href="{% url 'setlang' %}">{% trans "English" %}</a> views.py def setlang(request): logger.error(get_language()) if get_language() == 'de': activate('en') else: activate('de') logger.error(get_language()) return redirect('index') Output from logger.error(get_language()) -> 'de' than 'en'. It's everytime 'de'! Even if I set LANGUAGE_CODE = 'en'! I've no idea where the 'de' is coming from. The problem is maybe the reload, which is forced by the return redirect('index')? Translation in general works. Has anyone an idea how I can stick to the language which is selected and not fall back to default? -
Access to Django Session with React
I'm new to React and I wanna Access my Django sessions with React framework. In this case I have an array in my session named UserInfo that I can access with request.session['UserInfo'] in Django. I wanna know how can I get UserInfo data in React side and work with it? Literally how can we get or pass data from frontend to backend between these two? -
What is the best way to use phone number and validation code in django?
I want to bulid a backend appliaction in django, an i want to have authatication using only phone number, after the client write the phone number he will get a code via sms what is the best way to approch this ? how can i modify the login and authaticate methods in django base user model -
Django ADFS mock for unit tests
I use django_auth_adfs in my app. I need to mock it to perform view tests. The thing is that I've no idea which object should I mock. This is my one of my test used before installation of django_auth_adfs and fixture draft. class TestAPIVew: API_URL = reverse("list") @pytest.fixture def adfs(self): with patch('object_to_mock') as mock_auth: yield mock_auth def test_view_returns_correct_json(self, client, adfs): response = client.get(self.API_URL) data = response.json() assert response.status_code == HTTPStatus.OK assert data == {"key": "value"} QUESTION What should I do to omit authentication etc to make the test work as the user is logged in"