Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Connecting Django web application to python class library
I have a Django web application that runs couple of apps, I want this Django application to connect with the the other python project [which is not a web application] that has it's own data base. What I am trying to achieve is, when a user inputs a keyword and clicks search button in the django application the call has to go to the python project and execute the functionalities that it offers and display the results in the django application web page. If someone can explain me on how to achieve this that would be great. -
Celery connection to Redis throwing "timed out" error only when delay method called from Django view
I am perplexed with this error and looking for some expert help. Here are the details - I am running a Django application with celery to schedule and execute tasks I use Azure Cache for Redis as the celery backend and broker Azure Redis has SSL port enabled and non-SSL port disabled I have configured SSL using URL scheme (rediss://) as well as celery config (broker_use_ssl and redis_backend_use_ssl) My Task is defined in one django app and the view is in another (though they are deployed together) Everything works also fine in my local setup, where I don't use SSL on redis My django server is running with gunicorn inside a docker container Everything works just fine when celery-beat schedules a task and workers pick them up to execute. They both are able to communicate with Redis fine. However, when I call a task from my django view directly, with delay function, I see a timeout error on connecting Redis. Here is how I am calling the task (removed some boilerplate code for brevity): from mydjangoapp import tasks def MyViewFunction(request): tasks.MyTask.delay(param1, param2, param3) Here is the error I see : kombu.exceptions.OperationalError: Error while reading from <my-redis-server-url>:6380: ('timed out',) Can someone … -
Django No Reverse Match Failure to Supply int:pk
I am trying to create a hyperlink that takes a admin user to a sepearte web page where they can select a respective ingredient and update the quantity and price per unit. When I click on the update ingredient hyperlink to load that page Django says there is a no reverse match error. Error Message: `Traceback (most recent call last):= Exception Type: NoReverseMatch at / Exception Value: Reverse for 'ingredientupdate' with no arguments not found. 1 pattern(s) tried: ['ingredient/update/(?P<pk>[0-9]+)\\Z']` urls.py path('ingredient/update/<int:pk>', views.UpdateIngredientView.as_view(success_url = "/ingredients/"), name='ingredientupdate'), views.py `class UpdateIngredientView(UpdateView): # I am thinking this is an UpdateView model = Ingredient template_name = 'inventory/form_template.html' fields = ["quantity", "price_per_unit"]` success_url = reverse_lazy('ingredientupdate')` form_template.html form_template.html {% extends "inventory/base.html" %} {% block content %} <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"/> </form> {% url 'ingredientupdate' Ingredient.pk %} {% endblock %} After researching stack overflow articles: What is a NoReverseMatch error, and how do I fix it? it confirms to me that I need to supply the int:pk. In my template I supplied a Ingredients.pk but that was not enough. What exactly am I supposed to pass in? -
Does Django have any text file search features?
I am using Django Web Framework to store PDF files in FileFields, that will then be converted to .txt files to be used later. Does Django have any features to parse files for queries? My first thought if they diddn't was to use a simple Inverted Index, but I wanted to utilize Django tools as much as I can. I've done several searches in the Django documentation but haven't found anything. I know that the chance of Django having a feature like this was quite low. -
Django - URL pattern not found (page not found)
urls.py file from django.contrib import admin from django.urls import include, path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('employees/', include('employees.urls')), path('customers/', include('customers.urls')), path('courses/', include('courses.urls')), path('planning/', include('planning.urls')), path('intranet/', include('intranet.urls')), path('', include('dashboard.urls')), path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')), path('accounts/', include('accounts.urls')), path('api/', include('api.urls')), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) customers/urls.py file from django.urls import path from . import views app_name = 'customers' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('calendar/', views.CalenderView, name='calendar'), path('add/', views.addCustomerView, name='add_customer'), path('manage/<id>/', views.ManageCustomerView, name='manage_customer'), path('child/<mother_id>/add', views.addChildView, name='add_child'), path('child/manage/<id>', views.manageChildView, name='manage_child'), path('appointment/add', views.addAppointmentView, name='add_appointment'), path('appointment/<int:customer_id>/add', views.addAppointmentView, name='add_appointment'), path('appointment/<int:pk>/manage', views.manageAppointmentView, name='manage_appointment'), ] customers/views.py file def manageAppointmentView(request, pk): a = Appointment.objects.get(id=pk) if request.method == 'POST': form = AppointmentForm(request.POST, instance=a) if form.is_valid(): # create a new `Appointment` and save it to the db a = form.save() # redirect to the detail page of the appointment we just created # we can provide the url pattern arguments as arguments to redirect function return redirect('customers:customer', Appointment.customer_id) else: form = AppointmentForm(instance=a) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) Now, when I navigate to the following url: http://127.0.0.1:8000/customers/appointment/5/manage/ I get a page not found error even though the exact url can be found on row 10. What am I missing? The 'add_appointment' url is working perfectly fine. It's only the manage_appointment that is not … -
Django Model use a seperate model within model as if it is a past of it
I'm trying to accomplish the following; I have a model customer and model vendor (and others). I would like to have the fields of the model Location available within the customer and vendor models. What I can think of is to create the field similar available in the customer and vendor model, and have a seperate save function on each. What is the best approach? I can think of using the save function, and adding additional code to additionally create a Location entry and using that entry to update the location foreign key, meaning I need to have the field available in both Models. But is there a more efficient / proper approach? def save(self, *args, **kwargs): code to create or update the location entry super(Customer, self).save(*args, **kwargs) class Location(models.Model): type = models.CharField(max_length=30) street = models.CharField(max_length=30) number = models.CharField(max_length=30) postal = models.CharField(max_length=30) country = models.CharField(max_length=30) class Vendor(models.Model): name = models.CharField(max_length=30) location = models.ForeignKey(Location,on_delete=models.CASCADE) class Customer(models.Model): name = models.CharField(max_length=30) location = models.ForeignKey(Location,on_delete=models.CASCADE)``` -
CS50w Mail project won't print a simple console.log command to the console [closed]
Im currently working my way through the CS50w course working on project nr 3 "Mail" Designing a front-end for an email client that makes API calls to send and receive emails. The program is pre-written, the assignment is to only work with the JS and HTML. My issue is that I can't seem to send a POST request, or anything else for that matter. First I tried to solve the problem on my own, but could not get the "POST" request to get through. Looking at the Network tab in the console view I could only see the GET request loading the from prewritten code. I then followed a tutorial where they got it working. I followed it to the letter without changing anything and can't get a simple print statement to work. I tried deleting and restarting the program without changing anything but without success. Not even a simple print statement after the DOMContentLoaded would print. I don't get any error messages or logs to indicate what seems to be the problem. It just wont print anything on the console. Any help would be greatly appreciated! This is the tutorial I was following, solution starts from 05:14. https://www.youtube.com/watch?v=mj6q0gHOddY&t=438s I've … -
Django Cors-Origin resource sharing error MissingAllowOriginHeader
Hello friend i have problem, i tried many things but Nothing worked. This error appeares only for font-awesome font files and debug.js for django debug toolbar. application is deployed in GCP cloud run. static files are in Cloud Storage. application reads every other files. also connected from local to Cloud Storage and have same error Django version 4.1 django-cors-headers==4.2.0 settings.py from corsheaders.defaults import default_methods ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ ... 'corsheaders', ] CORS_ORIGIN_DOMAINS = [ 'http://localhost:8000' ] CSRF_TRUSTED_ORIGINS = CORS_ORIGIN_DOMAINS CORS_ALLOWED_ORIGINS = CORS_ORIGIN_DOMAINS CORS_ALLOW_METHODS = default_methods MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ... ] I tried: CORS_ORIGIN_ALLOW_ALL = True MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', ] MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST= [ 'http://localhost:8000' ] CORS_ALLOW_HEADERS = "*" INSTALLED_APPS = [ 'corsheaders', ... ] CORS_ALLOW_HEADERS = [ "accept", "accept-encoding", "authorization", "content-type", "dnt", "origin", "user-agent", "x-csrftoken", "x-requested-with" ] -
validated_data returns empty dictionary on update
I am building a backend system like Udemy, in this Cart API I am trying to update a cartitem object (a student want to add another course instead of this one) so I want to change the course in the cartitem and change the total_price of the cart. What happens is that when I update the course field it returns HTTP_200_OK response status but the body of the response is the JSON object of the exact same object before updating and the object is not updated models.py class Cart(models.Model): id = models.UUIDField(primary_key=True, default=uuid4) student = models.OneToOneField( User, on_delete=models.CASCADE, related_name='cart') total_price = models.IntegerField(default=0) class CartItem(models.Model): cart = models.ForeignKey( Cart, on_delete=models.CASCADE, related_name='items') course = models.ForeignKey(Course, on_delete=models.CASCADE) views.py class CartItemViewSet(ModelViewSet): http_method_names = ['get', 'post', 'put', 'delete'] def get_queryset(self): return CartItem.objects.filter(cart_id=self.kwargs['cart_pk']) def get_serializer_class(self): if self.request.method == 'PUT': return UpdateCartItemSerializer elif self.request.method == 'POST': return CreateCartItemSerializer else: return CartItemSerializer def get_serializer_context(self): return { 'cart_id': self.kwargs['cart_pk'] } serializers.py class CartItemSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) student_id = serializers.SerializerMethodField(read_only=True) def get_student_id(self, cart_item): return Cart.objects.filter(id=self.context['cart_id'])[0].student_id class Meta: model = CartItem fields = ['id', 'student_id', 'course_id'] class CreateCartItemSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) def create(self, validated_data): instance = CartItem.objects.get(cart_id=validated_data['cart_id'], course_id=validated_data['course_id']) try: return instance except CartItem.DoesNotExist: instance = CartItem.objects.create(**validated_data) instance.save() return instance class Meta: … -
How do I set cookies for redirection?
I'm working on a small project, and I want to set cookies when a user tries to redirect to a short URL. What does that mean? I am working with the Django framework and have written a function that creates a short url from a full url. Now I'm trying to set cookies for redirection, but it doesn't work. When I try to navigate to a short URL, I see a loading screen without redirecting to the full URL, so how can I fix this? My code bellow: def get_cookie(url): session = requests.Session() session.get(url) cookie = session.cookies.get_dict() return cookie def get_full_url(url: str) -> str: cookie = get_cookie('http://127.0.0.1:8000/'+url) try: link = Links.objects.get(short_url__exact=url) if not link.is_active: raise KeyError('Token is no longer available') except Links.DoesNotExist: raise KeyError('Try another url. No such urls in DB') if not cookie: link.unique_requests_count +=1 link.save() return link.full_url def redirection(request, short_url): try: full_link = get_full_url(short_url) response = HttpResponseRedirect(full_link) response.set_cookie('unique', short_url, max_age=None) return response except Exception as e: return HttpResponse(e.args) -
CORS for Django rest framework
I'm planning to make an app with Vue.js in the frontend and Django rest framework in the backend, so I was playing around with a small test app, but I can't figure out the correct CORS settings. I see many people online having issues with this, but none of the solutions seems to work for me. Below you can find the code of the files that might be relevant. I tried everything mentioned in this, this and this article and many more. Things that I tried are: add corsheaders to installed apps, add the middleware (at the top of the middleware list, as suggested in the docs), set CORS_ALLOW_ALL_ORIGINS to True, set CORS_ALLOWED_ORIGINS, set ALLOWED_HOSTS and CORS_ALLOWED_HEADERS to ['*'], set the proxy in the vue.config file and using a different browser/clearing browser cache. I believe the problem is in the backend, and the frontend is configured OK, but to be sure I'm also including the frontend files. Calling the view directly in the browser works fine (it does not use any authentication). The error that I get in the console is Access to XMLHttpRequest at 'http://localhost:8000/users' from origin 'http://127.0.0.1:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present … -
Cannot activate venv & there is no 'Scripts' Folder
I'm trying to make a venv, but the activation step, is not working and raises error below: 'activate' is not recognized as an internal or external command, operable program or batch file. First of all I'm using windows-OS, but the files that made by the command: python -m venv env_name are: click here to see the files pic. and instead of 'Scripts' Folder it made 'bin' Folder. Anyway, I've tried this code: env_name//bin/activate. But instead of making the env, it raised the error that i mentioned before. i will be appreciated if someone help. thanks -
how to setup a django modelform with ranges of dates and times
I have a submission modelForm set up with a submission model that consists of mostly char fields but I want to add a datetime field that has a datetime start and datetime end. What is the best way to set something like this up? |------ char data 1 |------ char data 2 | F__ range --- start datetime | O data --- end datetime | +? R M------ char data 3 | | ... | Each rangedata will go with one specific submission of the form, so there could be multiple start and end datetimes. I have tried setting up a separate datetime range model that has a foreign key to relate back to the submission model that will take in two datetimes but I am unsure of how to change the submission form form to now include the datetime range model. Would inlineformset_factory be the correct way forward? Or just the formset_factory from forms? Do I also need a separate datetime range form to be rendered within the parent submission form? I ideally would like an array of start/end tuples in the rangedata column in my database but I'm not sure if that's possible. A separate database linked to … -
Sending Notification to admin using Django Channels
Hy… i am working an leave system where i want when user submit leave form then admin receive notification that particular user request for leave, so amdin can approve or decline it. Form submission is done and for notification iam using Django Channels, I have configure django channels and also its dependencies, now websocket connection is established successfully and iam sending data form front end (websocket king client) to my backend (terminal) and it is working. But as i discuss above the main part is i want to send leave application data to admin so admin can receive notification and approve or decline it. I think for this we need to use channel_layer and send data to consumer and iam doing the same but it is not working and iam little bit confused about its flow that how data flow from user to admin. This is my view function… def leaveForm(request): if request.method == "POST": try: leaveData = { 'employeeLeave': request.user, 'leaveApplyDate': request.POST.get('leaveApplyDate'), 'leaveEmployeeName': request.POST.get('leaveEmployeeName'), 'leaveEmployeeId': request.POST.get('leaveEmployeeId'), 'leaveEmployeeDepartment': request.POST.get('leaveEmployeeDepartment'), 'leaveEmployeeDesigination': request.POST.get('leaveEmployeeDesigination'), 'leaveType': request.POST.get('leaveType'), 'leaveCategory': request.POST.get('leaveCategory'), 'leaveReason': request.POST.get('leaveReason'), # 'leaveStatus': request.POST.get('leaveStatus'), 'leaveNoDays': request.POST.get('leaveNoDays'), 'leaveDateFrom': request.POST.get('leaveDateFrom'), 'leaveDateTo': request.POST.get('leaveDateTo'), 'leaveDateHalfDay': request.POST.get('leaveDateHalfDay'), 'leaveTimeFrom': request.POST.get('leaveTimeFrom'), 'leaveTimeTo': request.POST.get('leaveTimeTo'), 'leaveOtherReasons': request.POST.get('leaveOtherReasons'), 'leaveStatus':'Pending' } print("leaveData",leaveData) leave_type = request.POST.get('leaveType') … -
Django STATIC not working when special characters in path
I am using STATIC to be able to call my css and js files in my templates. But i noticed every time there is a character like a space or a dash or some other special character it converts it to url and then it doesn't find the file for example, i have the following css static/ css/ template-style-min.css no in my template when i call it like this <link rel="stylesheet" href="{% static 'css/template-style-min.css' %}"> I keep getting a 404 on it, and i see in the logs its trying to call it like this "GET /static/css/template-style-min.css%3Fv%3D1.0.0 HTTP/1.1" 404 1892 Not sure why it keeps adding that to the end of the css file. Can't figure it out. -
Displaying an image in Vue.js using Django REST
I saved an image from user forms to mssql as binary data, now I want to display the image in user profile. I am working in Vuejs, Django and MSSQL. But there seems to be a problem with the URL as the image is not displaying. Backend is working fine, but there is an issue with Frontend When the image is fetched using GET method, it displays a pic icon, but image is not displayed because it says there is an issue with the URL, any ideas how to solve this In MSSQL, image is set as data type "image" this is my code: views.py: class studentPictures(APIView): def get(self, request, cnic, *args, **kwargs): try: stdpics = StudentPictures.objects.filter(std_cnic=cnic).first() # Serialize the StudentPictures instance serializer = StudentPicturesSerializer(stdpics) return Response(serializer.data, status=status.HTTP_200_OK) except StudentPictures.DoesNotExist: return Response({"error": "Student Pictures not found"}, status=status.HTTP_404_NOT_FOUND) except Exception as e: return Response({"error": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) def put(self, request, cnic, *args, **kwargs): print("put called", cnic) stdpics_data = StudentPictures.objects.filter(std_cnic=cnic).first() if stdpics_data is not None: image = request.FILES['image'] file_content = image.read() stdpics_data.image= file_content serializer = StudentPicturesSerializer(instance=stdpics_data,data= request.data,partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response({"res": "Object does not exist"}, status=status.HTTP_400_BAD_REQUEST) models.py: class StudentPictures(models.Model): std_pic_id = models.AutoField(primary_key=True) std_cnic = models.ForeignKey(Student, models.DO_NOTHING, … -
Django / JS How to make the enter key act like Tab in form
I would like to do the same thing than this : $('input').keypress(function(e) { if (e.which == 13) { $(this).next('input').focus(); e.preventDefault(); } }); But in a Django form rendered in a template with {{form}} to change the enter key behavior in my form and focus the next element each time it's pressed (to act like Tab). What should I replace the input by ? -
TimeoutError Exception in Django Web App When Using Sockets
I am encountering a TimeoutError exception in my Django web application when attempting to establish socket connections. The code snippet responsible for this issue is as follows, and it works correctly (detects correctly if the ip is accesible or not). However, the problem is that once I visit this particular section and execute the socket code, the TimeoutError continues to occur in all sections of my web app, even when they don't use the socket functionality. I have imported the 'socket' library and am using it to check if a specific IP is connected. Unfortunately, I cannot replace the socket with a ping command, as I need to deploy this web app on a server that does not have the 'ping' command available. Any insights into why this TimeoutError is propagating across all sections of my web app after being triggered in one specific section, and how to resolve it, would be greatly appreciated. socket.setdefaulttimeout(0.5) # create a socket object mi_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: # try to connect to endpoint bol = mi_socket.connect_ex((ip, port)) print('ip:', ip) print('bol:', bol) if bol == 0: connected = 'True' else: connected = 'False' mi_socket.close() except Exception: traceback.print_exc() mi_socket.close() connected = 'False' I have … -
Where does model store data in django?
I'm trying to define non-database models (Position and Portfolio). # models.py class Position(models.Model): code = None price = None value = None class Meta: managed = False def __init__(self, code, price, value): self.code = code self.price = price self.value = value class Portfolio(models.Model): positions = [] class Meta: managed = False def add(self, position): self.positions.append(position) class PositionSerializer(serializers.ModelSerializer): class Meta: model = Position fields = ['code', 'price', 'value'] # serializers.py class PortfolioSerializer(serializers.ModelSerializer): positions = PositionSerializer(many=True) class Meta: model = Portfolio fields = ['positions'] # views.py class PortfolioDetail(APIView): """ List all portfolios, or create a new portfolio. """ def get(self, request, analyzer_id, date, format=None): logger.warning('requesting portfolio using {} on {}'.format(analyzer_id, date)) portfolio = Portfolio() portfolio.add(Position('600519', 1900.0, 50000)) serializer = PortfolioSerializer(portfolio) return Response(serializer.data) The problem is every time I refresh the page, the position in portfolio will be added. That means there will be multiple positions after page refreshing. Why? -
Pass data to already running Celery task in Django
I have a Dajngo application that runs Celery task like @shared_task(bind=True) def start_serial_acquisition(self, idObj, porta_COM): __cycle_over_something__ launched with start_serial_acquisition.delay(instance.pk, porta_COM) Is there a way to, knowing the task id, to send data (i.e. a variable/dicitonary/list) to an already running celery task? Because the Celery task have to do a certain number of instruction cyclically for a certain number of time, my idea was to use Redis with a fixed key, and read on every cycle the key. The Django application will write on the specific Redis key when needed. The task will do something if the value read from the key is a certain value This idea is a bit of a workaround as, I would prefer something more event driven -
how to assign users during a data migration in django?
I know this seems like it should be a no-brainer and should work without fail, but I am getting a crazy error during a migration which is currently running during pytest initialization. The error I am getting is: ValueError: Cannot assign "<User: redshred_default_contact>": "Client.primary_contact" must be a "User" instance. When i stop in the debugger on the offending line, i get the following: -> isinstance(default_user, User) True -> isinstance(default_user, get_user_model()) True My migration is as follows: # Generated by Django 4.2.4 on 2023-09-14 18:13 from django.db import migrations from django.contrib.auth import get_user_model from django.contrib.auth.models import Group, User from django.conf import settings def assign_default_client(apps, schema_editor): Client = apps.get_model("apiserver_v2", "Client") client = Client.objects.get(slug="default-client") get_user_model().objects.update(account__client=client) def create_default_client(apps, schema_editor): (default_user, _) = User.objects.get_or_create(username="default_contact") default_user.save() Client = apps.get_model("apiserver_v2", "Client") # BUG: this is where the bug is occurring client = Client.objects.create( name="Default Client", slug="default-client", primary_contact=default_user, domain="mydomain.com", ) (group, _) = Group.objects.get_or_create(name="default_contact_group") client.new_user_group = group client.save() class Migration(migrations.Migration): dependencies = [ ("apiserver_v2", "0026_account"), ("authtoken", "0003_tokenproxy"), ] operations = [ migrations.RunPython(create_default_client, migrations.RunPython.noop), migrations.RunPython(assign_default_client, migrations.RunPython.noop), ] My Client model is: from django.contrib.auth import get_user_model from django.db import models from shortuuid.django_fields import ShortUUIDField class Client(models.Model): """A Client represents one of our clients. Clients are used for accounting purposes. All … -
Django Issue Filtering by Date Occupied
I have a Unit model and a HistoricalOccupancy model in my project. The HistoricalOccupancy tracks the move in and move outs of my units. I am trying to run a report where given a selected month and year, I can dictate that a Unit was occupied or not, but the logic for how to define it is not working in my head. class HistoricalOccupancy(SafeDeleteModel, TimestampModel, UUID): """ Used to track a running talley of move-ins and move-outs """ id = models.AutoField(primary_key=True) unit = models.ForeignKey('units.Unit', on_delete=models.CASCADE, db_column='unit_id', related_name='historical_occupancy') # update fields on each residents_at_move_in = models.ManyToManyField('residents.Resident', related_name='move_in_historical_occupancy') residents_at_move_out = models.ManyToManyField('residents.Resident', related_name='move_out_historical_occupancy') move_in_date = models.DateField() move_out_date = models.DateField(null=True, blank=True) Given that model, and a date like today datetime.datetime(day=1, month=9, year=2023) how can I find out if the unit was occupied during that time? This doesn't work because the move in date isn't relevant: for unit in units: # find if unit was occupied during month selection for h in unit.historical_occupancy.filter( move_in_date__gte=datetime.datetime(day=1, month=9, year=2023), move_out_date__lte=datetime.datetime(day=1, month=9, year=2023) ): print('yay') Also note that move out date can be none, meaning it is currently occupied at the existing moment in time. -
React Native Django Authentication: TypeError: Cannot read property 'isLoggedIn' of undefined
I'm implementing a Django authentication system in my React Native app. My app.js imports the authentication context, so isLoggedin on app launch is false. The variable isLoggedIn is used in app.js to either render the login screen when isLoggedIn is false, else load AppNavigator which gets the user into the app. I haven't written the Django backend yet, I'm just setting isLoggedIn to true when the login button is pressed without talking to Django (until I get this problem solved). The program execution stops at: line 15 of App.js: const { isLoggedIn } = globalContext; I've double checked all relevant import statements and believe I'm exporting and importing correctly. Also double checked the import paths. I also made sure isLoggedin and setIsLoggedIn are in the globalContext variable in AuthContext.js. It is being passed into the Context.Provider in AuthContext.js and App.js is wrapping the whole app in Provider, so the auth context is available to the whole app. The app should show the login screen on first load. I should be able to enter some text in the 2 text fields and press the login button to get into the app. However, Expo Go displays the error "TypeError: Cannot read property … -
Run Django-Q along with Django's management command runserver
I'm using Django-Q to run some background tasks and schedules. Currently facing two problems here: When stopping the django-q cluster using CTRL+C the cluster is not getting stopped properly. Not sure if this is an OS specific issue. I'm using Windows Even when the django server is stopped, since the django-q cluster is running, the configured schedules are also running. So I'd like for a way to start and stop the django-q cluster along with the django server itself I was looking for a way to start the django-q cluster to start along with the django server by modifying the manage.py file but not sure if it is advisable. and not sure what's the correct way to do it -
Python - Get result of an update query (Mysql) when performing raw SQL
I work on a Django project and need to apply changes in an other remote DB (not Django DB). Those changes are async and launched with Celery. But when performing these queries, I need to know if updates are well done with counting affected rows, otherwise I must take corrective action. Until now, I haven't found any way to do this. I tried with cusr.fetchone() and curs.fetchall() but results are None. When I print(curs.execute()), the result is 0 even if the product is found. This thread says it should be 1 if update is done. Even the official documentation doesn't talk about this. So, for the time, the only workaround I found is performing a first SELECT query and if rowcount < 1, I raise an Exception. Not really nice ... Is there a way to do it better ? Nota : I use django.db.backends.mysql and pymysql