Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
subdomain is not redirecting to main domain but different virtual host
I am hosting multiple domains from the same server. Each domain is having multiple subdomains. Let's say I have the following domains: example1.com, and example2.com. Also, example1.com have subdomain1.example1.com. I redirect http to https with SSL certificate on exmaple1.com and *.example1.com and example2.com. My example1.com and example2.com redirected fine but subdomain1.exmaple1.com is not redirecting and it is trying to get the certificate from example2.com. My application is Django and I am using mod-wsgi for deployment. Thanks in advanced -
How to launch a Postgresql database container alongside an Ubuntu Docker image?
How do you use docker-compose to launch PostgreSQL in one container, and allow it to be accessed by an Ubuntu 22 container? My docker-compose.yml looks like: version: "3.6" services: db: image: postgres:14-alpine environment: - POSTGRES_USER=test - POSTGRES_PASSWORD=test - POSTGRES_DB=test command: -c fsync=off -c synchronous_commit=off -c full_page_writes=off --max-connections=200 --shared-buffers=4GB --work-mem=20MB tmpfs: - /var/lib/postgresql app_test: build: context: .. dockerfile: Dockerfile shm_size: '2gb' volumes: - /dev/shm:/dev/shm My Dockerfile just runs a Django unittest suite that connects to the PostgreSQL database using the same credentials. However, it looks like the database periodically crashes or stops and starts, breaking connection with the tests. When I run: docker-compose -f docker-compose.yml -p myproject up --build --exit-code-from myproject_app I get output like: Successfully built 45c74650b75f Successfully tagged myproject_app:latest Creating myproject_app_test_1 ... done Creating myproject_db_1 ... done Attaching to myproject_app_test_1, myproject_db_1 db_1 | The files belonging to this database system will be owned by user "postgres". db_1 | This user must also own the server process. db_1 | db_1 | The database cluster will be initialized with locale "en_US.utf8". db_1 | The default database encoding has accordingly been set to "UTF8". db_1 | The default text search configuration will be set to "english". db_1 | db_1 | Data page … -
Can not use Django-rest-auth in Django4.0 ; ImportError: cannot import name 'ugettext_lazy' from 'django.utils.translation'
For now I am building the Django Rest Framework in Django4.0 and Django-rest-auth. I knew the django4.0 does not support the ugettext_lazy. it support the gettext_lazy instead of. I installed the django-rest-auth==0.9.5 in my app. and then it raised the issue. ImportError: cannot import name 'ugettext_lazy' from 'django.utils.translation' Here is my settings: THIRD_PARTY_APPS = [ 'escapejson', 'corsheaders', 'rest_framework_swagger', 'rest_framework', 'rest_auth', 'drf_yasg', 'django_jsonfield_backport', 'allauth', 'allauth.account', 'allauth.socialaccount', ] INSTALLED_APPS = LOCAL_APPS + DJANGO_APPS + THIRD_PARTY_APPS In Django4.0, Can not I use the django-rest-auth? -
Field 'id' expected a number but got <>ManyRelatedManager object
I am trying to remove a field in a many to many relationship but I came across this error and I dont know how to solve/fix it. Here is what I am trying to do: 1: Before the below views I get a valid POST from user identifing data.log_order 2: I search if there are previous logs in ActiveSession. If there is search for matching logs with the same received data.log_order and delete the existing one and add the new received data. 3: If there is no matching data.log_order in log or previous logs to add the new received data. As simple as the logic as difficult as I am struggling to get my errors fixed. class Log(models.Model): ................................... log_order = models.IntegerField(validators=[MinValueValidator(1)],blank=True, null=True) class LogForm(forms.Form): ............................. log_order = forms.IntegerField() class ActiveSession(models.Model): log = models.ManyToManyField(Log, related_name='savedlogs') .................................. Here is the views: if active_session.log.values(): print(active_session.log.values()) for i in active_session.log.values(): if i['log_order']==int(data.log_order): log_order = data.log_order log=Log.objects.filter(log_order=log_order) print(log) active_session = ActiveSession.objects.get(id=ActiveSession.objects.last().id,log__in=log) print(active_session) active_session.log.remove(active_session.log) active_session.log.add(data) print(active_session.log.values()) else: active_session.log.add(data) print(active_session.log.values()) print('Existing Log with different order_no') else: active_session.log.add(data) print('Log added to Session') print(active_session.log.values()) return HttpResponseRedirect(url) Here is the traceback: Traceback (most recent call last): File "C:\Users\User\Desktop\Portfolio\venv\lib\site-packages\django\db\models\fields\__init__.py", line 1774, i n get_prep_value return int(value) TypeError: int() argument must … -
How do I get a Django multiple select form to pass through selected items as a list?
I have a Django application where I use multi-select with dynamic choices as related to the logged-in user, but when I try to submit the form, I keep getting the following error message: "TypeError at /masstext.html Field 'id' expected a number but got <QueryDict: {'customers': [''], 'textmessage': ['test'], 'csrfmiddlewaretoken': ['FNawscd4CXqtDWIUrq0Kolq3x6R699lStaykXwxDbtqciJortBm0pTfPWSvvjW7L']}>" I'd like to have it where, when the user submits the form, a new model instance is created with the selected customers and the message typed out as fields. I don't understand why I'm not getting a list of selected customers from the multi-select returned in the list, but rather an empty list. Code below: Model: class Masstext(models.Model): profile = models.ForeignKey(Profile, on_delete = models.CASCADE) message = models.CharField(max_length = 500, null = True) customers = models.CharField(max_length = 1000, null = True) Form: class Textform(ModelForm): def __init__(self, user, *args, **kwargs): super(Textform, self).__init__(*args, **kwargs) self.fields['customers'] = forms.ModelChoiceField( queryset = Customers.objects.filter(facility__profile__email = user)) class Meta: model = Masstext fields = ['customers','message'] View: @login_required(login_url="login/") def load_customers(request, *args, **kwargs): msg = '' if request.method == 'POST': user = request.user form = Textform(request.POST) if form.is_valid(): form.save() else: msg = "Fields are not valid" else: form = Textform(request.user) context = {'form': form} return render(request,'home/masstext.html',context) Template: <form action="masstext.html" method="POST"> … -
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>