Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
'QuerySet' object has no attribute 'products'
I want to get all products in table's order. but I see this error. can you help me with that? here my models: from django.db import models from products.models import Product # Create your models here. class Table(models.Model): table_number=models.IntegerField(unique=True) def __str__(self): return f'{self.table_number}' class Order(models.Model): products=models.ManyToManyField(Product,related_name='products_order') table=models.ForeignKey(Table, on_delete=models.CASCADE,related_name='orders') def __str__(self) -\> str: return f'{self.table.table_number} {self.products} and my views: class TableDetailView(View): def get(self,request,id): table=Table.objects.get(id=id) order=Order.objects.filter(table__id=id) products=order.products #here is the problem context={'table':table,'products':products,} return render(request,'orders/table_detail.html',context) I also tried: `products=order.products.all()\` But I got similar error. -
Django can't identify which input field is being pressed
I can't seem to recognize the problem in my django project - I have a simple form with 2 "input" tags and I can't identify in my code which one is being pressed. front end: <form method="POST"> {% csrf_token %} <input type="image" value="accept" class="v" src="{% static 'main/assets/icons/v.png' %}"> <input type="image" value="decline" class="x" src="{% static 'main/assets/icons/x.png' %}"> </form> back end: if response.method == "POST": if response.POST.get("accept"): return render(response, "main/calender-page.html", {}) if response.POST.get("decline"): return render(response, "main/account-page.html", {}) I tried to search for answers in stack overflow and I never managed to find one that works. Thanks for the help! -
Can I have html tags in Django admin panel?
can I have this entry with all these tools such as bold, italic, title, etc: I mean s.th like this photo instead of this: default panel I've found this solution, but I want s.th better enter image description here -
Search function not working in Django / Bootstrap
I am facing problems in search functionality of Django. the function is as follows: def search(request): if request.method == 'GET': query = request.GET.get('query','') allPosts = Post.objects.filter(Q(title__icontains=query) | Q(content__icontains=query)) return render(request, 'dn/search.html', {'allPosts':allPosts, 'query':query}) the search form is as under: <form class ="{% url 'search' %} d-flex" method="get"> <input class="form-control me-2" type="text" name="query" placeholder="Search" aria-label="Search"> <button class=" text-white text-uppercase fw-bold btn btn-outline-primary light border-1 rounded-pill border-white border border-1" type="submit">Search</button> </form> the search page is as under: {%extends 'dn/base.html'%} {% block title %} Search Results | active {% endblock title %} {% block content %} <div class="container"> {% if allposts %} {% for querry in allposts %} <div class="row"> <div class = "col md-12"> <h3>{{querry.title}}</h3> <br> </div> <div class="col-md-12"> <p>{{querry.content}} </p> </div> </div> {% endfor %} {% else %} <p><h3> No Search Results </h3></P> {% endif %} </div> {%endblock%} However, while searching anything in the system is not showing the results. can you please guide me what i am missing to get the results. Thanking you. Regards SSA -
Django session data is lost when using HttpResponseRedirect
I have two simple views: def form_view(request): form = MyModelForm() if request.method == "POST": form = MyModelForm(request.POST) if form.is_valid() form.save() uuid = uuid4() request.session["uuid"] = uuid.hex return HttpResponseRedirect(reverse("thanks")) return render(request, "form.jinja2", {"form": form}) # the url obtained by reverse("thanks") maps to this view def redirect_view(request): if "uuid" in request.session: # this returns false in prodcution return render(request, "thanks.jinja2", {"uuid": request.session["uuid"]} return redirect("/") The code works in development, i.e I can fetch data from request.session, but in production it does not work, and I can't seem to figure out why. I have tried to set request.session.modified = True, set SESSION_COOKIE_SECURE = False in settings and also tried using request.session.set_test_cookie() and request.session.test_cookie_worked() in the two different views, i.e setting the cookie in form_view and testing the cookie in redirect_view, but it returned false. Interestingly, if I do this: def form_view(request): form = MyModelForm() if request.method == "POST": print(request.session.test_cookie_worked()) # this prints True! form = MyModelForm(request.POST) if form.is_valid() form.save() uuid = uuid4() request.session["uuid"] = uuid.hex return HttpResponseRedirect(reverse("thanks")) request.session.set_test_cookie() return render(request, "form.jinja2", {"form": form}) The test_cookie_worked() returns True. I have tried many of the solutions recommended when searching on something similar, but none of these work for me, and I don't know what else … -
Filter table as per the multiple dropdown selection
I have created the table using datatables. So I want to filter table as per the multiple dropdown selection. But I have multiple table with the same data. Actually the columns are too much, so to avoid so scrolling I have added the tables into the multiple tabs. Like: In TAB1 (columns : ID, Origin, Destination) | TAB2 (columns : ID , Driver Type, Product Type) etc.. here is my dropdown html Code: <div class="row"> <div class="col"> <div class="input-group mb-6"> <span style="padding: 4px 10px ;">Route Volume ></span> <input type="number" id="filterByVolumeAddOne" class="form-control" style="max-width: 80px; padding: 1px;margin-right: 1em;" aria-describedby="basic-addon1"> <select class="form-control ml-3" style="width: 15em !important; margin-left: 10px !important;" id="productFilterDropdown" multiple> {% for op in products %} <option value="{{op.product_name}}">{{op.product_name}}</option> {% endfor %} </select> <select class="form-control ml-3" style="width: 20em !important;" id="equipmentFilterDropdown" multiple> {% for op in Equipments %} <option value="{{op.equipment_name}}">{{op.equipment_name}}</option> {% endfor %} </select> <select class="form-control ml-3 mr-3" style="width: 15em !important;" id="driverFilterDropdown" multiple> {% for op in drivers %} <option value="{{op.driver_type}}">{{op.driver_type}}</option> {% endfor %} </select> <div class="input-group-prepend"> <span class="input-group-text" id="filterByVolumeGreater" style="background-color: #2980b9; color: aliceblue; padding: 6px; cursor: pointer;"><i class="fa fa-arrow-right"></i></span> </div> </div> </div> </div> table html code of TAB1: <table class="table dataTable table-striped table-bordered" id="routeData"> <thead class="thead-dark"> <tr> <th style="z-index: 2 !important;"></th> <th style="z-index: … -
Django model validation which uses a ManyToMany field
I have a model like this: class Offer(models.Model): condition_products = models.ManyToManyField( "shop.Product", blank=True, help_text="User needs to own at least one of these products.", ) condition_owned_after = models.DateField( blank=True, null=True, help_text="User needs to own at least one products after this date.", verbose_name="Owned after date", ) It's for a webshop where we can create offers with certain conditions. One of the conditions is that the user needs to already own one or more products, and a second condition is that this products needs to be owned after a certain date. I want to add validation to the model so that condition_owned_after can only be filled in when condition_product_variants is not None. But when I try to access condition_product_variants in the clean method I get a ValueError from Django. class Offer(models.Model): # ... def clean(self): if self.condition_owned_after and not self.condition_products.all(): raise ValidationError( { "condition_owned_after": "Cannot set condition_owned_after without also setting condition_products" } ) def save(self, *args, **kwargs): self.full_clean() return super().save(*args, **kwargs) This results in the following error: ValueError: "<Offer: Offer object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used I understand the error, but I don't understand how to work around it. How can I … -
Django is trying to use PSQL 9.6, while 12.15 is installed, raising a "raise NotSupportedError"
I verified that I actually have: (PostgreSQL) 12.15 (Ubuntu 12.15-1.pgdg22.04+1), when I run the command psql --version. When I run python3 manage.py dbshell, I get this result: psql (12.15 (Ubuntu 12.15-1.pgdg22.04+1), server 9.6.24) SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off) I tried ps aux | grep postgres and I see a list with only 12/main, and there is no 9.6.24 anywhere as the Error indicated. -
Only display the Value of a ForeignKey and not <model> object(...) in Template
I have a Django Modal with ForeignKeys. class clientvul(models.Model): client= models.ForeignKey(client, on_delete=models.CASCADE) VID=models.ForeignKey(vul, on_delete=models.CASCADE) Path=models.CharField(max_length=1000) Product=models.CharField(max_length=1000) isActive=models.BooleanField(default=True) class Meta: constraints = [ models.UniqueConstraint( fields=['client', 'VID'], name='unique_migration_host_combination' ) ] I've created a qs vul1=clientvul.objects.all() in a View. When I try to display the Data on a Template it Displays vul object(4803) I want to only display the 4803. -
ImportError: cannot import name 'reflections' from 'chatbot'
It doesn't work even I've imported from chatbot import Chat, reflections, multiFunctionCall.Let show me the way if you can deal with a issue It doesn't work even I've imported from chatbot import Chat, reflections, multiFunctionCall.I expect the way How to solve this problem