Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJango Redirect Not Refreshing the Page
I'm having an issue where "return redirect('/main')" is working but have to refresh the browser manually to see the change. From the main.html template, button onclick calls JS jpButton(), which does a work, then returns to DJango function that updates session value, then redirect to main page that will display the value in the session. But the value does not change on page until I manually refresh the browser. Please help. // jsbutton.js - called from onlick button in main template async function jpButton() { ... $.ajax({ type: "POST", url: 'http://localhost:8080/main/jpConnect', headers: { "X-CSRFToken": csrftoken }, data: { onlinestatus: "Online" }, .... ### views.py ### # This redirect works fine def jpDisconnect(request): request.session['onlinestatus'] = None return redirect('/main') # This is called from JS jpButton(), and the browse have to be manually refreshed afterwards def jpConnect(request): if request.headers.get('x-requested-with') == 'XMLHttpRequest': request.session['onlinestatus'] = request.POST.get('onlinestatus', None) return redirect('/main') <!-- main.html --> ... {% csrf_token %} {% if request.session.onlinestatus %} <a href="{% url 'jpDisconnect' %}"> <button class="button" type="button" > {{ request.session.onlinestatus }} </button></a> {% else %} <button class="button" type="button" onclick="jpButton()"> Offline </button></a> {% endif %} ... Strangely, the jpDisconnect() refreshes and changes the value on the page, but the jpConnect() does not (I have … -
How to get this Django REST query to display all fields, including fields from related one-to-one table
This is my Django models.py with 2 tables having a one-to-one table relationship. UserComputedInfo model has a one-to-one relationship with CustomUser model. from django.contrib.auth.models import AbstractUser from django.db import models from django.contrib.auth import get_user_model class CustomUser(AbstractUser): email = models.EmailField(unique=True) post_code = models.DecimalField(max_digits=9, decimal_places=6) def __str__(self): return self.username class UserComputedInfo(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) copy_input = models.DecimalField(max_digits=9, decimal_places=6) def __str__(self): return self.copy_input I am trying to create a REST API to display all the fields in the 2 tables. I am using Django REST framework. This is my serializers.py from rest_framework import serializers from users.models import CustomUser class CustomUserSerializer(serializers.ModelSerializer): class Meta: fields = ("email", "post_code") model = CustomUser This is my views.py from rest_framework import generics from django.contrib.auth import get_user_model from .serializers import CustomUserSerializer class PostCodeAPIView(generics.ListAPIView): queryset = get_user_model().objects.all() serializer_class = CustomUserSerializer The API will display all the fields in CustomUser table. However, I want to display all the fields in the related one-to-one UserComputedInfo table as well. I am using Django v4, python v3.9, Django REST framework on Windows 10. -
Render form dynamically on AJAX Request with Django
Introduction I think I'm mistaking something how (pure) AJAX and Django should be used while I try to implement the following: A view is displaying a list of all model's objects with buttons to change an existing object or to create a new one. Clicking on such a button opens a modal and fires an AJAX request to render the form A Django view is processing the request and is rendering the template for the requested form with Django's render_to_string Rendered string is returned as context with Django's JsonResponse Returned JSON is used for displaying form via JavaScript (modal.innerHTML) Form is filled by user and send with AJAX to a Django view where form data will be processed Response is given by view with JsonResponse and shows success or errors Since implementing step 5, I was wondering if I'm on the right track. Using render_to_string and JsonResponse leads to some extra space ahead of the form. This is caused by a BOM. To be specific, \ufeff is prepending the HTML containing string whereby the BOM is rendered (but not shown) by browser and causing the unwanted extra line. I did not found any other solution than using replace multiple times … -
Nginx, gunicorn, django not passing real IPV6 address
I am currently trying to set up a simple ip website, miip.co with the purpose of just showing your your ip address when you open the site. When I test https://ready.chair6.net/?url=https://miip.co it shows yes to all but ipv4 literals with only a warning. My nginx location looks like so location / { proxy_pass http://unix:/home/www/miip/app.sock; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Scheme $scheme; proxy_set_header REMOTE_ADDR $remote_addr; proxy_read_timeout 1000; # this } And my django ip function looks like so def get_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip Yet despite this, it always return a ipv4. My system is also on ipv6. I think it has to do with nginx proxy pass but unsure. -
Django add select2
i try to add the Select2 in my django app but i can't use it. What i do wrong ? Anyone have a solution ? page.html <!----Select2-----> <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" /> <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script> <!----Select2-----> <script> $(document).ready(function() { $('#id_employe').select2(); }); </script> Filter from the form -
How to extract values from Queryset Django
When an output is received in the below form after running the query <QuerySet [<key: value object (ad5bb6b4-8035)>]> I want to get ad5bb6b4-8035 string only for further operations. So I tried course_qs = <QuerySet [<key: value object (ad5bb6b4-8035)>]> for course in course_qs: print(course) which returned value object (ad5bb6b4-8035) How to get only ad5bb6b4-8035.? getting values of QuerySet in django How to extract numerical value from Django queryset? Extracting message from django queryset -
Image not saving to django models when trying to upload from react-native
I am writing my first react-native app with a django backend. In order for my app to function properly, I need to send an image from the react-native to django models. I am trying to send an image and then save it to the model, but when I check the django-admin the image field is empty. heres my code- react-native: const [ sentI, setSentI ] = useState(null) const sendI = async (image) => { const formData = new FormData() image_data = { uri : image.uri, name : "profileImage", type : 'image/jpg' } if (image != null){ await formData.append( 'image', image.uri,) await formData.append( 'name', usern,) setSentI(formData) console.log('recieved') } console.log(formData) } const showImagePicker = async () => { // Ask the user for the permission to access the media library const permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync(); if (permissionResult.granted === false) { alert("You've refused to allow this appp to access your photos!"); return; } let result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ImagePicker.MediaTypeOptions.All, allowsEditing: true, aspect: [4, 3], quality: 1, }); // Explore the result console.log(result); if (!result.cancelled) { await setProfileImage(result); console.log(result.uri); sendI(result); } } const image = () => { fetch(`http://192.168.5.234:8000/home/imagetest/`, { method: 'POST', body: { sentI }, }) .then( res => res.json()) .then( res … -
Django: self.model_set not accesible in custom save() function
I'm trying to make a custom save function that calculates some values and will store them in another Model to which a ManyToMany relationship exists. From what I can understand from the documentation, I should have a field_set way of accessing all the related objects. However, when I save here, I get the error 'Game' object has no attribute 'heat_set' I don't see what I'm doing wrong here: class Game(models.Model) heat = models.ManyToManyField(Heat) [...] def save(self, *args, **kwargs): super().save(*args, **kwargs) for heat in self.heat_set.all(): [...] -
Django Rest Framework value id is being sent, but is being received as null
Having an issue where I am trying to set the interest_category. Here is my current code. Serializer class ProjectsSerializer(serializers.ModelSerializer): interest_category = serializers.StringRelatedField() class Meta: model = Project read_only_fields = ( 'created_by', 'created_at', 'updated_at', ), fields = ( 'project_title', 'project_description', 'interest_category', ) Model class Project(models.Model): project_title = models.CharField(max_length=255) project_description = models.TextField(max_length=1500) interest_category = models.ForeignKey(Interests, on_delete=models.CASCADE) created_by = models.ForeignKey(User, related_name='projects', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) Views class ProjectViewSet(viewsets.ModelViewSet): serializer_class = ProjectsSerializer queryset = Project.objects.order_by('-created_at') def perform_create(self, serializer): serializer.save(created_by=self.request.user) Here is the data being sent { "project_title": "Test", "project_description": "Test1", "interest_category": 2 } Here is the data being received (35, Test, Test1, 2022-09-22 02:11:54.342202+00, 2022-09-22 02:11:54.342202+00, 1, null). I can send the data without a null error when I am NOT using the interest_category = serializers.StringRelatedField() in the serializer. Any ideas why the interest_category is showing null and why it is not being sent and/or received correctly when using the serializers.StringRelatedField()? And if it is because of the StringRelatedField is there a better way to get the name while posting the ID? In frontend, I am passing the ID as a value. -
best way to store celery results
I am using celery for my async tasks, however, I am using Redis as backend broker. My current plan is to filter and manipulate data inside the backend and store it into django-db for viewing etc. Is this the recommended way? Or I should use Django DB as backend results db and store all the raw data then filter and manipulate it into different tables? -
Django ORM query for filtering product price between two number is not working properly
class Product(models.Model): product_name = models.CharField(max_length=255,unique=True) slug = models.SlugField(max_length=255) brand = models.CharField(max_length=255) price = models.CharField(max_length=255) product_image_1 = models.ImageField(upload_to = 'photos/product',blank = False) product_image_2 = models.ImageField(upload_to = 'photos/product', blank = False) product_image_3 = models.ImageField(upload_to = 'photos/product', blank = False) product_image_4 = models.ImageField(upload_to = 'photos/product',blank = False) product_description = models.TextField() category_id = models.ForeignKey(Categories,on_delete=models.CASCADE) subcategory_id = models.ForeignKey(SubCategories, on_delete=models.CASCADE) stock = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) def __str__(self): return self.product_name def get_url(self): return reverse('product_detail',args = [self.category_id.slug , self.subcategory_id.slug, self.slug ]) '''view''' val=request.POST.get('value') val = re.findall("\d+", val) # code to get all inigers from string min_price = int(val[0]) max_price = int(val[1]) print(min_price) print(max_price) ***product = Product.objects.filter(category_id = categories,is_active = True,price__gte = min_price, price__lte = max_price)*** when i give value greater than max_value product object returns null object I want all objects between the two min_value and max_value -
Django is not serving my image asset, using rest framework
I am uploading an image file from Flutter to Django, the image is getting saved properly in my backends directory under assets/images, and when I query the database with a get I get the proper path of the file. But when I go to the URL in the browser the image does not appear and I get an error. I am using rest-framework for my app. Model: class Product(models.Model): supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) name = models.CharField(max_length=200) quantity = models.IntegerField(default=0) barcode = models.CharField(max_length=200) cost_price = models.FloatField(default=0) selling_price = models.FloatField(default=0.0) image = models.ImageField(upload_to='images/', null=True) Settings.py: MEDIA_ROOT = os.path.join(BASE_DIR, 'assets') MEDIA_URL = '/pm/assets/' Urls.py: urlpatterns = [ path('', include(router.urls)), ] urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Serializer: class SuppliersSerializer(serializers.ModelSerializer): product_set = ProductsSerializer(read_only=True, many=True) class Meta: model = Supplier fields = ['pk','user','name','email','phone','product_set'] class ProductsSerializer(serializers.ModelSerializer): transactions_set = TransactionsSerializer(read_only=True, many=True) class Meta: model = Product fields = ['pk','name','quantity','barcode','cost_price','image', 'selling_price', 'transactions_set'] JSON response: { "pk": 13, "name": "pi3", "quantity": 3, "barcode": "11111", "cost_price": 10.0, "image": "/pm/assets/images/533a6ac0-f682-4814-9237-89df8e02fda715039130977982609.jpg", "selling_price": 20.0, "transactions_set": [] }, But when visiting: http://localhost:8000/pm/assets/images/533a6ac0-f682-4814-9237-89df8e02fda715039130977982609.jpg I get this error: -
Is there any way with django tables2 to only show data based off any given information
I have looked all over not sure if I am searching to broadly. I want to essentially only show data to a user if that user is linked to the data. Currently it shows all data. Example of similar function. {% for group in request.user.groups.all %} {% if group.name == 'General User' %} {% for project in project_card_list %} {% for u in project.assigned_users.all %} {% if u == user %} This is just a quick example of what I want, I was able to display the data this way but was wanting to clean it up and have it show in a django table2 table instead. Table code: class ProjectTable(tables.Table): class Meta: model = Project template_name = "django_tables2/bootstrap.html" fields = ("name", "project_lead", "start_date", "end_date", "description") exclude = ("project_id", "assigned_users",) View: @login_required(login_url='login_register') def projects_page(request): table = ProjectTable(Project.objects.all()) return render(request, 'projects.html', {'table': table}) -
Tools used to build Stack Overflow
Creating a blog site is difficult what should I use Django and heroki or what ?? What should a blog Site Contain ? Can I create an alternative to Stack Overflow -
hi i have problem with django and front_end
I want to build an online store and I want to enter the number of products that the customer wants to enter in the front and then send it to Django, for example, if he says 6 apples, I will change the number of apples to 6 in Django. -
Having a problem integrating this google calendar keep getting null setting src (Netsuite)
this is my code, and I am trying to be able to switch between different calendars. But it wont let me function googleCalendars(portlet, column) { var calendarSelect; portlet.setTitle("Sportex Calendars"); calendarSelect = portlet.addField("calendar_select", "select", "Select Calendar"); calendarSelect.setHelpText("Select a calendar"); calendarSelect.addSelectOption("humanresources", "Human Resources"); calendarSelect.addSelectOption("vacation", "Vacations"); calendarSelect.addSelectOption("appointments", "Appointments"); portlet.addField("calendar", "inlinehtml", "Some HTML").setLayoutType("outsidebelow", "startrow").setDefaultValue("" + "<div>" + '<<iframe src="https://calendar.google.com/calendar/embed?height=600&wkst=1&bgcolor=%23ffffff&ctz=America%2FPhoenix&showCalendars=0&src=c3BvcnRleGNhbGVuZGFyQGdtYWlsLmNvbQ&src=YWRkcmVzc2Jvb2sjY29udGFjdHNAZ3JvdXAudi5jYWxlbmRhci5nb29nbGUuY29t&src=ZW4udXNhI2hvbGlkYXlAZ3JvdXAudi5jYWxlbmRhci5nb29nbGUuY29t&src=aHQzamxmYWFjNWxmZDYyNjN1bGZoNHRxbDhAZ3JvdXAuY2FsZW5kYXIuZ29vZ2xlLmNvbQ&color=%23039BE5&color=%2333B679&color=%230B8043&color=%23B39DDB" style="border:solid 1px #777" width="1200px" height="600px" frameborder="1" scrolling="no"></iframe>' + "</div>"); portlet.addField("resizer", "inlinehtml", "CSS Overrides for Portlet Content Resizing").setDefaultValue("" + "<style>" + "ns-script-portlet-content-wrapper iframe," + "#main_form table, #cal_frame {" + "width: 100%;" + "}" + "</style>"); portlet.setScript("customscript_googlecalendar_client")} function fieldChange(type, name) { if(name == "calendar_select") { if(nlapiGetFieldValue("calendar_select") == "humanresources") { document.getElementById("cal_frame").src = "https://calendar.google.com/calendar/embed?src=833451c59dcb80fff2263f6cfb17fa5ae246b70d97588f1ef46ffbc04658433b%40group.calendar.google.com&ctz=America/Phoenix" }else { if(nlapiGetFieldValue("calendar_select") == "vacation") { document.getElementById("cal_frame").src = "https://calendar.google.com/calendar/embed?src=f61df42873f6d090babb273c46cd295f12795c08647b8c18088d25691cb653fb%40group.calendar.google.com&ctz=America%2FPhoenix" }else { if(nlapiGetFieldValue("calendar_select") == "appointments") { document.getElementById("cal_frame").src = "https://calendar.google.com/calendar/embed?src=clto48tqq2vmp19sfuqra8oprc%40group.calendar.google.com&ctz=America/Phoenix" } } }}nlapiResizePortlet()}; -
Always Defer a Field in Django
How do I make a field on a Django model deferred for all queries of that model? Research This was requested as a feature in 2014 and rejected in 2022. Baring such a feature, the obvious idea is to make a custom manager like this: class DeferedFieldManager(models.Manager): use_for_related_fields = True def __init__(self, defered_fields=[]): super().__init__() self.defered_fields = defered_fields def get_queryset(self, *args, **kwargs): return super().get_queryset(*args, **kwargs ).defer(*self.defered_fields) class A(models.Model): big_field = models.TextField(null=True) b = models.ForeignKey(B, related_name="a_s") objects = DeferedFieldManager(["big_field"]) class B(models.Model): pass class C(models.Model): a = models.ForeignKey(A) class D(models.Model): a = models.OneToOneField(A) However, while this works for A.objects.first() (direct lookups) and B.objects.first().a_s.all() (one-to-manys), it doesn't work for C.objects.first().a (many-to-ones) or D.objects.first().a (one-to-ones). An easy way to test this is to drop the field that should be deferred from the database, and the code will only error with an OperationalError: no such column if the field is not properly deferred. How do I make this field deferred for all ways this model is loaded (without needing to put a defer call on every query)? -
Django/python retrieving integer value from models.integerfield
class Trainingvalue(models.Model): maximalvalue= models.PositiveIntegerField(null=True,blank=True) How can I retrieve integer from maximal value , in order to use in a views.py function like to create another variable to render it to context dictionary ? -
django-filter IN lookup filter and list of strings
Using Graphene in Django to create Gql schema, now trying to filter Foreign Keys with list of strings. It kinda works, but not exactly. schema.py class CharInFilter(BaseInFilter, CharFilter): pass class ProductFilter(FilterSet): softwares__name = CharInFilter(field_name="softwares__name", lookup_expr="in") class Meta: model = Product fields = {"name": ["exact", "icontains"]} class ProductType(DjangoObjectType): class Meta: model = Product filterset_class = ProductFilter interfaces = (graphene.relay.Node,) query query authorPageProducts { user(slug: "john") { productSet(softwares_Name: "Blender") { edges { node { name softwares { name } } } } } } Here is what works and what not: softwares_Name: "Blender" -> correct softwares_Name: "Houdini" -> correct softwares_Name: "Blender,Houdini" -> empty result, not correct I am passing string separated with comma. Can/should I pass list of strings in Gql query? Im not sure if its possible/necessary. I do have Products that have both Foreign Keys with values "Houdini" and "Blender", so query with "Blender,Houdini" shouldn't be empty. I tried this query in shell, and its correct. Here I used list of strings. u = User.objects.get(id=2) p = u.product_set.filter(softwares__name__in=["Blender", "Houdini"]) Here is some info from Django Debug Toolbar, to see SQL expression for third case. SELECT COUNT(*) AS "__count" FROM "shop_product" INNER JOIN "shop_product_softwares" ON ("shop_product"."id" = "shop_product_softwares"."product_id") INNER JOIN "shop_software" … -
Unable to search from hacker news api django
I would like to search different items (jobs, stories, ask) from the hacker news api but I can't seem to figure out how to do it correctly, please check code below and tell me what I'm doing wrong as I'm unable to run it successfully. def search(request): if 'search' in request.GET: search = request.GET['search'] url = 'https://hacker-news.firebaseio.com/v0/item/{item-id}.json?print=pretty' response = requests.get(url) article_list = response.json() context = {} context['objects'] = [] for each_id in article_list[:10]: # Make a separate API call for each article. url = f"https://hacker-news.firebaseio.com/v0/item/{each_id}.json" # get response for individual articles response = requests.get(url) article_dict = response.json() context['objects'].append(article_dict) return render(request, 'SyncNews/search.html', context) {% for x in objects %} <h3 class="news-subheading">{{ x.title }}</h3> {% endfor %} <form method="GET" action="{% url 'search' %}"> <input type="text" name="item-id" placeholder="Search" /> </form> -
Default task list in new instance of 'To Do' app in Django
I am learning Django and creating ToDo app. I need to get a hint on logic how to implement default task list while user is creating a new record (instance) of ToDo app. Simply, I want to avoid hardcoding of any specific task list into the HTML, rather I want to have pre-populated (based on app specifics) model class (from Django Admin) which will be added to ToDo app instance during CreateView. Also I wish to implement 'add task' feature within the ToDo app instance i.e. add any extra task user wants on top of default tasks. Hope my question is clear. -
DRF return JsonResponse from another function
I am trying to return the JsonResponse from another function but I get the following error from DRF: AssertionError: Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a <class 'NoneType'> Here is my code class SignedURL(GenericViewSet): queryset = fileUpload.objects.all() serializer_class = fileUploadSerializer def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) function1(request) def function1(request): return JsonResponse( { "message": "Pass", }, status=status.HTTP_400_BAD_REQUEST, How can I return the JsonResponse from another function without writing return JsonResponse in the def create itself? Further clarification: I have ten different functions with ten different Jsonresponses. ie, function2,function3...function10. If for example, function 4 fails, I would like to return the JSON response immediately from that function and not to proceed further with the other functions within the create call. -
Problem while creating a mofelform and editing a particular field in the modelform
I am in a middle of a project. The problem is arising from here : class PatientCreation(forms.ModelForm): class Meta: model = Patient fields = ['user','contact'] dob = forms.DateField(widget=forms.SelectDateWidget(years=range(1960,2022))) Whenever i try to save the form by using the frontend its creating an error. The model for this form is : class Appointments(models.Model): doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE) patient = models.ForeignKey(Patient, on_delete=models.CASCADE) app_time = models.DateTimeField() diognoses = models.TextField(max_length=1000) prescriptions = models.TextField(max_length=250) class Meta: unique_together = ('doctor', 'patient', 'app_time') def __str__(self): st = (str(self.doctor.user.name)+str(self.patient.user.name)).lower().strip() return st I am not sure if i can even define a particular field in a model form or not else the widget is working fine. So how can I implement the logic such that I get the date time widget in dob field. Also how can i default the value of the user field as the currently logged in user. -
django app app crashing when opening on heroku
I'm trying to open my heroku app but i keep getting the 'heroku logs --tail' error. I checked the logs and the only error I can see is: 'ImportError: cannot import name '_sanitize_token' from 'django.middleware.csrf' (/app/.heroku/python/lib/python3.10/site-packages/django/middleware/csrf.py)' FYI, I had some issue with the _sanitize_token when trying to run my server with manage.py before deploying. I had to change some settings in tastypies authentication: original(wouldn't let me run server): from django.middleware.csrf import _sanitize_token amended(this let me run the server): import django.middleware.csrf Now, I don't know wether the error above is actually causing the crash or if i should be looking into this: at=error code=H10 desc="App crashed" TYIA for any help on this -
how to add django-database-size to django project view?
I am trying to use django-database-size to display mysql table sizes to django admin page. The project has very limited docs to how to add the view. Here is the repo: https://github.com/chrisspen/django-database-size All it mentions about adding the view: Install the appropriate view in /sql (currently only PostgreSQL and MySQL supported).