Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I cannot retrieve the corresponding data when I want to relate the foreign key with the User object
models.py class Order(models.Model): PAYMENT_OPTIONS = ( ('VISA','VISA'), ('Master','Master'), ('Octopus','Octopus'), ('Cash','Cash'), ) STATUS = ( ('Pending','Pending'), ('Delivered','Delivered'), ) user = models.ForeignKey(User,models.CASCADE,null=True,blank=True) customer = models.CharField(max_length=200,null=True,blank=True) card_id = models.IntegerField(null=True,blank=True) mobile = models.IntegerField(null=True,blank=True) email = models.CharField(max_length=200,null=True,blank=True) total_price = models.DecimalField(decimal_places=2,max_digits=7) payment_method = models.CharField(max_length=50,choices=PAYMENT_OPTIONS,null=True,blank=True) status = models.CharField(max_length=50,choices=STATUS,default='Pending') date = models.DateTimeField(auto_now_add=True) address = models.CharField(max_length=350,null=True,blank=True) def __str__(self): return str(self.customer)+'\'s Order' views.py def order_summary(request,order_id): customer_order = Order.objects.get(id=order_id) food_order = OrderDetail.objects.filter(order=customer_order) context = { 'customer_order':customer_order, 'food_order':food_order} return render(request,'menu/order_summary.html',context) navbar.html <li><a class="dropdown-item" href="{% url 'order_summary' [order_id]%}我的訂單</a></li> For the above code, I may want to have the hyperlink that can access the order_summary method with filtering the correct User object. However, if I want to filter out the object in Order model with the user equals to the current request.user, I am not sure what should I put in the order_id in the hyperlink because the navbar could not recognize the correct object in the Order model so can anyone explain? -
create API by using generic.ListAPI take too much time
I am creating API in django by using generic.ListAPI when i hit this API it take too much time approx. 5 min. Below is my code what mistake i did can anybody help me class KeyMarket(generics.ListAPIView): queryset = UserAddress.objects.all() serializer_class = UserAddressSerializer def list(self, request, *args, **kwargs): b = [] add = [] filter_data=UserAddress.objects.filter(address_type='1') serializer = self.get_serializer(filter_data, many=True) b.append(serializer.data) for i in range(len(serializer.data)): c = serializer.data[i] add.append(c['address']) re = set(add) return Response(re) -
How to keep the razorpay id secret in the html that is being passed as a context for processing the payment?
I am using an .env file to keep the variables out of the settings.py but the razorpay_id that is supposed to be a secret can still be seen by inspecting the element of the page in which the id is being passed in the context. How I can keep it a "secret" or what is the process to keep that id a "secret" in the html too during the entire payment process. this is the codes that I am using. .env RAZORPAY_ID=test_id RAZORPAY_ACCOUNT_ID=test_id settings.py RAZORPAY_ID = env('RAZORPAY_ID') RAZORPAY_ACCOUNT_ID = env('RAZORPAY_ACCOUNT_ID') views.py client = razorpay.Client(auth=(settings.RAZORPAY_ID , settings.RAZORPAY_ACCOUNT_ID)) context={ 'razorpay_merchant_id': settings.RAZORPAY_ID, } html <script> var options = { "key": "{{razorpay_merchant_id}}", } </script> -
Django access information model with foreign key
my models.py class Information(models.Model): id = models.CharField(max_length=200, primary_key=True) title = models.CharField(max_length=500) link = models.CharField(max_length=100) summary = models.CharField(max_length=1000) published = models.CharField(max_length = 100) def __str__(self): return self.title class Search(models.Model): id = models.CharField(max_length=100, primary_key=True) searched_titles = models.CharField(max_length=100) searched_topics = models.CharField(max_length=100) number_found_articles = models.IntegerField() def __str__(self): return self.id class Article_search(models.Model): found_articles = models.ForeignKey( Information, on_delete=models.CASCADE, default=None, primary_key=True) search_details = models.ForeignKey( Search, on_delete=models.CASCADE) my views.py def show_articles_with_this_filter_id(request): alles = Article_search.objects.all() print(alles) the error i get: (1054, "1054 (42S22): Unknown column 'database_article_search.found_articles_id' in 'field list'", '42S22') if i make my models.py Article_search class like this: class Article_search(models.Model): found_articles = models.ForeignKey( Information, on_delete=models.CASCADE, default=None) search_details = models.ForeignKey( Search, on_delete=models.CASCADE) I get this error: (1054, "1054 (42S22): Unknown column 'database_article_search.id' in 'field list'", '42S22') It seems like I need to specify an ID or so. Please can someone help me to access the data from this model -
Django custom admin template has_change_permission is always None
I have a custom admin template where I need to check has_add_permission and has_change_permission values. I can see that the has_add_permission has True/False according to the permission assigned to the user. The value of has_change_permission is always None. For instance: {% if has_add_permission %} {# The condition has a True/False value #} ... {% endif %} {% if has_change_permission %} {# Never executed because the condition is always None #} ... {% endif %} How can I determine if the user can change a table? -
Nginx not serving static files and user uploaded files in Django Kubernetes
Hi i am working on a kubernetes and can't get static files or user documents. This runs behind nginx ingress all queries and django works as expected. But unable to figure out why images and other documents cant be obtained via url. Application gets installed using helm charts and functionality seems to be okay other than serving files. FROM python:3.8.12-alpine3.15 ADD ./requirements.txt /app/requirements.txt RUN set -ex \ && apk add --no-cache --virtual .build-deps postgresql-dev build-base linux-headers jpeg-dev zlib-dev\ && python -m venv /env \ && /env/bin/pip install --upgrade pip \ && /env/bin/pip install --no-cache-dir -r /app/requirements.txt \ && runDeps="$(scanelf --needed --nobanner --recursive /env \ | awk '{ gsub(/,/, "\nso:", $2); print "so:" $2 }' \ | sort -u \ | xargs -r apk info --installed \ | sort -u)" \ && apk add --virtual rundeps $runDeps \ && apk del .build-deps ADD ./ /app WORKDIR /app ENV VIRTUAL_ENV /env ENV PATH /env/bin:$PATH RUN apk add nginx RUN rm /etc/nginx/http.d/default.conf COPY helm/nginx.conf /etc/nginx/nginx.conf ENTRYPOINT ["sh", "helm/run.sh"] run.sh nginx -g 'daemon on;' gunicorn main_app.wsgi:application --bind 0.0.0.0:8080 --workers 3 nginx.conf user nginx; worker_processes auto; error_log /var/log/nginx/error.log; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; # default_type application/octet-stream; access_log /var/log/nginx/access.log; upstream … -
Configuration of MYSQL connectivity in django framework
Well, I'm trying to connect MYSQL database to Django , I have installed mysql installer 8.0 version, after installation in the Accounts and Roles section its not taking root account password and also I m not getting to change the password option, please help if anyone faced the same problem , let me know if any solution for this . How do I change the MYSQL root account password -
ValueError: Cannot query "sohanur": Must be "CustomUser" instance
I am trying to filter my vendor list as per request.user.vendor. It is working and get the requested user but here I can't query through my Vendor list. Vendor has a onetoone relation with my custom user. How to query?? #this is my model class CustomUser(AbstractUser): number = models.CharField(max_length=200, blank=True, null=True) isVendor = models.BooleanField(default=False, blank=True, null=True) class Vendor(models.Model): user = models.OneToOneField(CustomUser, related_name='vendor', on_delete=models.CASCADE, null=True, blank=True) distributor_for = models.ManyToManyField(Distributor, null=False, blank=True) name = models.CharField(max_length=200, blank=True, null=True) profile_picture = models.ImageField(null=True, blank=True) address = models.TextField(max_length=2000, blank=True, null=True) latitude = models.DecimalField(max_digits = 13, decimal_places = 7, blank=True, null=True) longitude = models.DecimalField(max_digits = 13, decimal_places = 7,blank=True, null=True) is_verified = models.BooleanField(default=False) createdAt = models.DateTimeField(auto_now_add=False, null=True, blank=True) def __str__(self): return self.name #this is my api view @api_view(['GET']) @permission_classes([IsVendor]) def getVendors(request): user = request.user.vendor print(user) vendor = Vendor.objects.all().filter(user=user) serializer = VendorSerializer(vendor, many=False) return Response(serializer.data) #this is my serializer class VendorSerializer(serializers.ModelSerializer): user = serializers.SerializerMethodField(read_only=True) class Meta: model = Vendor fields = '__all__' def get_user(self, obj): user = obj.user serializer = UserSerializer(user, many=False) return serializer.data -
How can i get all related object's manytomany related field's records in Django by single query
class Author(models.Model): name = models.CharField(max_length=50) class Chapter(models.Model): book = models.ForeignKey(Album, on_delete=models.CASCADE) author = models.ManyToManyField("Author") class Book(models.Model): author = models.ManyToManyField("Author") I can get Author.objects.get(id=1).chapter_set.all() and append each chapters author to the List but how can i achieve this by query in Django -
Django unable to save FloatField value to 0.0
I have a method on a model that updates a value to 0.0 and calls save(). Problem is save() is never saving the value if it is 0. Here is the code: class Item(models.Model): stock_quantity = models.FloatField( null=True, blank=True, validators=[MinValueValidator(0)] ) class Meta: abstract = True ordering = ["-id"] def mark_as_finished(self) -> None: self.stock_quantity = 0.0 self.save() I have a submodel which extends this one. class Instance(Item): expiration_date = models.DateField(null=True, blank=True) Now the mark_as_finished() is called in the view: @action(detail=True, methods=["patch"], url_name="mark-as-finished") def mark_as_finished(self, request: Request, pk: int) -> Response: pi_instance = get_object_or_404(Instance, id=pk) pi_instance.mark_as_finished() pi_instance.refresh_from_db() return Response( data=self.serializer_class(pi_instance).data, status=HTTP_200_OK, ) Upon running the test the stock value never becomes 0. def test_mark_as_finished(self): pink_ins = self.create_sample_instance() self.assertNotEqual(pink_ins.stock_quantity, 0) url: str = reverse(self.mark_finished_url, kwargs={"pk": pink_ins.id}) res: HttpResponse = self.client.patch(url) self.assertEqual(res.status_code, 200) self.assertEqual(res.data["stock_quantity"], 0) self.assertEqual(res.data["stock_quantity"], 0) AssertionError: 10.5 != 0 I am debugging the program and can see that after the save runs the value is never being saved. If I put the value as 0.1 then it saves. So actually it is not saving 0 value in the float field. I even removed the MinimumValueValidator still it won't save 0 value. -
Django Forms ChoiceField is not showing options; remains hidden
views.py def rank(request): if request.method == 'POST': form = RankRegisterForm(request.POST or None) if form.is_valid: form.user = request.user form.save(commit=False) return redirect('matches/rank.html') else: form = RankRegisterForm() return render(request, 'matches/rank.html', {'form': form}) forms.py class RankRegisterForm(forms.ModelForm): rank = forms.ChoiceField(choices=rankChoices) class Meta: model = Rank fields = ( "rank", ) html {% extends 'base.html' %} {% block content %} {% if user.is_authenticated %} <div class="container"> <p> Belt Rank Status </p> <form method="POST"> {% csrf_token %} {{ form.as_p }} <button class="red-text text-darken-1" type="submit">Submit</button> <br></br> </form> </div> {% endif %} {% endblock content %} models.py class Rank(models.Model): user = models.OneToOneField( CustomUser, on_delete=models.CASCADE, primary_key=True, ) rank = models.CharField("rank", max_length=20, choices=rankChoices) rankPoints = models.IntegerField("rank points", default=0) certificateOfLegitimacy = models.BooleanField(default=False) promoted = models.BooleanField(default=False) def __str__(self): return self.rank + ", " + self.user.email DOM <form method="POST"> <input type="hidden" name="csrfmiddlewaretoken" value="ITC0cjPUCmvhuYD2K1eDgjPOt1daSRJbi8mbpLmv6ETGVe9akMI2SOfjEJQcXJ9A"> <p> <label for="id_rank">Rank:</label> <select name="rank" id="id_rank"> White Blue Purple Brown Black thanks, this sucks. I've been looking everywhere and there isn't a question related to mine that has been answered. It's hidden, i suspect it's because of the csrf shit. but idk. help a brother out. -
How to update bokeh embedded map from HTML in Django?
I am making flight tracking application. Everything seems to be ok in code but when I run it map loads perfectly fine but flights or points in bokeh map loads only after refreshing page for 3 times. I couldn't manage to add periodic call back which loads data for map. Here are the code, can you please show me the right way? <script> function refresh_bokeh() { $.ajax({ url: '{% url 'index' %}', success: function(div) { alert("page reloaded") $('#map').html(div); } }); } setTimeout(function(){ refresh_bokeh(); },5000); </script> and main part of html to be loaded is <body> <div id="main"> <div id="map"> {{div|safe}} {{script|safe}} </div> </div> </body> Views.py code is here below: # Create your views here. def index(request): #FUNCTION TO CONVERT GCS WGS84 TO WEB MERCATOR #DATAFRAME def wgs84_to_web_mercator(df, lon="long", lat="lat"): k = 6378137 df["x"] = df[lon] * (k * np.pi/180.0) df["y"] = np.log(np.tan((90 + df[lat]) * np.pi/360.0)) * k return df #POINT def wgs84_web_mercator_point(lon,lat): k = 6378137 x= lon * (k * np.pi/180.0) y= np.log(np.tan((90 + lat) * np.pi/360.0)) * k return x,y #AREA EXTENT COORDINATE WGS84 lon_min,lat_min=-125.974,30.038 lon_max,lat_max=-68.748,52.214 #COORDINATE CONVERSION xy_min=wgs84_web_mercator_point(lon_min,lat_min) xy_max=wgs84_web_mercator_point(lon_max,lat_max) #COORDINATE RANGE IN WEB MERCATOR x_range,y_range=([xy_min[0],xy_max[0]], [xy_min[1],xy_max[1]]) #REST API QUERY user_name='' password='' url_data='https://'+user_name+':'+password+'@opensky-network.org/api/states/all?'+'lamin='+str(lat_min)+'&lomin='+str(lon_min)+'&lamax='+str(lat_max)+'&lomax='+str(lon_max) # init bokeh column data … -
Can't UPGRADE django from macOS terminal
I'm trying to upgrade django old version 2.2.5 so I can install the new one 4.0.2 I have both python Python 2.7.17 and Python 3.7.4 installed on my MacBook Air (macOS 12.2.1). When I try to uninstall django through 'pip3 uninstall django' i get a traceback error. I was trying to uninstall django so I can install the new version since is really outdated. *ERROR: Exception: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/shutil.py", line 566, in move os.rename(src, real_dst) PermissionError: [Errno 13] Permission denied: '/Library/Frameworks/Python.framework/Versions/3.7/bin/pycache/' -> '/private/var/folders/s7/p9l82rrs71g8df756700_4rh0000gn/T/pip-uninstall-labg_6ws' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/ABA/Library/Python/3.7/lib/python/site-packages/pip/_internal/cli/base_command.py", line 167, in exc_logging_wrapper status = run_func(args) File "/Users/ABA/Library/Python/3.7/lib/python/site-packages/pip/_internal/commands/uninstall.py", line 99, in run verbose=self.verbosity > 0, File "/Users/ABA/Library/Python/3.7/lib/python/site-packages/pip/_internal/req/req_install.py", line 638, in uninstall uninstalled_pathset.remove(auto_confirm, verbose) File "/Users/ABA/Library/Python/3.7/lib/python/site-packages/pip/_internal/req/req_uninstall.py", line 369, in remove moved.stash(path) File "/Users/ABA/Library/Python/3.7/lib/python/site-packages/pip/_internal/req/req_uninstall.py", line 267, in stash renames(path, new_path) File "/Users/ABA/Library/Python/3.7/lib/python/site-packages/pip/_internal/utils/misc.py", line 305, in renames shutil.move(old, new) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/shutil.py", line 578, in move rmtree(src) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/shutil.py", line 516, in rmtree return _rmtree_unsafe(path, onerror) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/shutil.py", line 400, in _rmtree_unsafe onerror(os.unlink, fullname, sys.exc_info()) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/shutil.py", line 398, in _rmtree_unsafe os.unlink(fullname) PermissionError: [Errno 13] Permission denied: '/Library/Frameworks/Python.framework/Versions/3.7/bin/pycache/django-admin.cpython-37.pyc' Can anyone help me? Thanks! -
Can't install django project dependencies using pipenv install
I want to install Django project in fresh ubuntu 20.04. The project requires python3.9, so I installed python3.9 using sudo apt install python3.9 python3-pip then I installed django using pip. Now I want to install the project dependencies using pipenv install here is the error I get: mahdi@mahdi-Latitude-E6430:~/Desktop/Project1$ pipenv install Creating a virtualenv for this project… Using /usr/bin/python3.9 (3.9.5) to create virtualenv… ⠋created virtual environment CPython3.9.5.final.0-64 in 429ms creator CPython3Posix(dest=/home/mahdi/.local/share/virtualenvs/Project1-UUOFIsQX, clear=False, global=False) seeder FromAppData(download=False, pip=latest, setuptools=latest, wheel=latest, pkg_resources=latest, via=copy, app_data_dir=/home/mahdi/.local/share/virtualenv/seed-app-data/v1.0.1.debian.1) activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator Virtualenv location: /home/mahdi/.local/share/virtualenvs/Project1-UUOFIsQX Pipfile.lock (6ab9a1) out of date, updating to (5b3760)… Locking [dev-packages] dependencies… Locking [packages] dependencies… 1] File "/usr/lib/python3/dist-packages/pipenv/patched/piptools/resolver.py", line 72, in resolve_hashes return {ireq: self.repository.get_hashes(ireq) for ireq in ireqs} File "/usr/lib/python3/dist-packages/pipenv/patched/piptools/resolver.py", line 72, in <dictcomp> return {ireq: self.repository.get_hashes(ireq) for ireq in ireqs} File "/usr/lib/python3/dist-packages/pipenv/patched/piptools/repositories/pypi.py", line 274, in get_hashes return { File "/usr/lib/python3/dist-packages/pipenv/patched/piptools/repositories/pypi.py", line 275, in <setcomp> self._get_file_hash(candidate.location) File "/usr/lib/python3/dist-packages/pipenv/patched/piptools/repositories/pypi.py", line 282, in _get_file_hash for chunk in iter(lambda: fp.read(8096), b""): File "/usr/lib/python3/dist-packages/pipenv/patched/piptools/repositories/pypi.py", line 282, in <lambda> for chunk in iter(lambda: fp.read(8096), b""): File "/usr/lib/python3/dist-packages/pipenv/vendor/pip9/_vendor/requests/packages/urllib3/response.py", line 324, in read flush_decoder = True File "/usr/lib/python3.9/contextlib.py", line 135, in __exit__ self.gen.throw(type, value, traceback) File "/usr/lib/python3/dist-packages/pipenv/vendor/pip9/_vendor/requests/packages/urllib3/response.py", line 237, in _error_catcher raise ReadTimeoutError(self._pool, None, 'Read timed out.') pip9._vendor.requests.packages.urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed … -
Django Rest Framework communicating with mobile app instances
I would like to build a REST Service which exchanges JSON messages with instances of a mobile app for registering patron traffic in physical locations of (public and academic) libraries. I plan on using Django Rest Framework, and using Django and DRF for the first time, have some questions (rather, recommendation requests). I have read the tutorials and followed some of them, and it looks very promising indeed. As I am quite confident with Object oriented coding in Python, I will be using class based views. Any reason not to? The intended usage of the system will include many different libraries with their own ids, users and properties. The data model behind is thus fairly complex, and implemented with MySQL. I feel I will have better control on the data exchange, updates inserts and selects, with custom SQL queries, and would like the DRF to handle mostly authentication and the routing of messages to and from the instances of the mobile app. Is this a misconception on my part, and would it be better to let DRF handle all database-involved aspects? Given that I follow the custom SQL approach: As (authenticated) user IDs are interwoven with the rest of the … -
Django PostModel request.user isLiked. How can I do that for Every Post?
For each of my posts, I want to send the data whether the logged in user likes it or not. My Post Model: class ModelPost(models.Model): user = models.ForeignKey(ModelUser,on_delete=models.CASCADE) title = models.CharField(max_length=100) Its my View: class ViewHomePage(View): http_method_names = ["get"] def get(self,request): posts = ModelPost.objects.all() # I want For each article I want to post whether that user liked it or not return render(request,"homepage.html",{"posts":posts}) I want to use it like this in template {% for post in posts %} {% if post.isLiked %} <h1>YES IT'S LIKED FROM REQUEST.USER (LOGGED USER) {% else %} <h1>NO IT'S NOT LIKED FROM REQUEST.USER (LOGGED USER) {% endif %} {% endfor %} How can I do that for EVERY POST -
Limit Choices for Charfield
I have a model for all choices in program. Instead of Choices Tuple , i wanna use this table for showing options and validate from table when it's gonna save. So it's not gonna be static as tuple choices in model. class FIELD_CHOICES(models.Model): groupName = models.CharField(max_length=120, null=True, blank=True) value = models.CharField(max_length=120, null=True, blank=True) key = models.CharField(max_length=120, null=True, blank=True) active = models.BooleanField(default=True, blank=True) Main problem is , i'm using charfield for choices right now and it should stay as charfield for other reasons. So i can't use Foreing key model type and limit_choices_to option. There are Also a lot of choices field in program so overriding save method is not best practice in this situation. Is there any option to keep it as charfield and validate from another table ? A custom model field or anything else ? -
TypeError: 'Answer' object is not iterable
class AnswerListFilterForUserView(APIView): def get(self, request, pk): user = request.query_params.get('user') data = Answer.objects.filter(question = pk).filter(username = user).order_by('created_at').last() serializer= AnswerFilterSerializer(data, many=True) return Response(serializer.data) How can i get last data from my Answer Model When i am use last() then error occurs That "TypeError: 'Answer' object is not iterable" Help me out of this -
How to add Scrapy project in Django project?
I want to use scrapy in my Django projects. Does anyone tell me what the structure will be? How can I save the scraped data saved in Django models and display it in Template View? -
Django admin query sum quantity for each type for each request.user
the issue is that i have 3 users levels 1-superuser 2-jihawi 3-mahali, I would like to separate the veiw from the "Quantite" function by request.user models.py class typestock(models.Model): Type = models.CharField(max_length=50, blank=True, null=True) def __str__(self): return self.Type class stock(models.Model): Jihawi = models.ForeignKey(User, on_delete=models.CASCADE, related_name="stockjihawi", editable=True, blank=True, null=True) Mahali = models.ForeignKey(User, on_delete=models.CASCADE, related_name="stockmahali", editable=True, blank=True, null=True) Date = models.DateField(blank=True, null=True) TypeStock = models.ForeignKey(typestock, on_delete=models.CASCADE, editable=True, blank=True, null=True) Quantite = models.IntegerField() def save(self, *args, **kwargs): super(stock, self).save(*args, **kwargs) return self.TypeStock admin.py class TypeStockAdmin(nested_admin.NestedModelAdmin, ImportExportModelAdmin): inlines = [InlineStock] list_display = ('Type', 'Quantite') list_display_links = ('Type',) list_filter = ('Type',) search_fields = ('Type',) def Quantite(self, obj): result = stock.objects.filter(TypeStock_id=obj).aggregate(Sum("Quantite")) return result["Quantite__sum"] Quantite.short_description = "Quantité" how to add this code in the Quantite function: if request.user.is_superuser: stock.objects.filter(StockType_id=obj).aggregate(Sum("Quantity")) ###must view all quantity from stock models### elif request.user.is_jihawi: stock.objects.filter(TypeStock_id=obj).aggregate(Sum("Quantity")) ###how to add filter Jihawi=request.user (Jihawi from stock models)### elif request.user.is_mahali: stock.objects.filter(StockType_id=obj).aggregate(Sum("Quantity")) ###how to add filter Mahali=request.user (Mahali from stock models)### -
Django: Difference between blank=True and default=""
When declaring a model, there are many questions about null vs blank arguemnts. But what is the difference between if I mark a django.db.models.CharField with default="" vs blank=True ? To me it seems like the same concept? -
DjangoListField() vs graphene.List() in Graphene Django
I used both "DjangoListField()" and "graphene.List()". "DjangoListField()" in schema.py: import graphene from graphene_django import DjangoObjectType from graphene_django import DjangoListField from .models import Category class CategoryType(DjangoObjectType): class Meta: model = Category fields = ("id","name") class Query(graphene.ObjectType): all_categories = DjangoListField(CategoryType) # Here def resolve_all_categories(root, info): return Category.objects.all() "graphene.List()" in schema.py: import graphene from graphene_django import DjangoObjectType from .models import Category class CategoryType(DjangoObjectType): class Meta: model = Category fields = ("id","name") class Query(graphene.ObjectType): all_categories = graphene.List(CategoryType) # Here def resolve_all_categories(root, info): return Category.objects.all() Then, I queried "allCategories": query { allCategories { id name } } But the result is the same: { "data": { "allCategories": [ { "id": "1", "name": "category1" }, { "id": "2", "name": "category2" } ] } } What is the difference between "DjangoListField()" and "graphene.List()"? -
creating a dynamic range slider in django and javascript but it's not working
I'm trying to make a dynamic range slider, but it's not work. I know basic Javascript. I want to make a slider like that If I change the price of the servers by changing the number in the slider, it would indicate the servers whose price is the same. Django template <div class="form-group numeric-slider"> <div class="numeric-slider-range ui-slider ui-slider-horizontal ui-slider-range"></div> <span class="numeric-slider-range_text" id='st_text'> </span> <input type="range"> </div> {% for i in page_obj %} ... {% endfor %} <script> $(function () { $(".numeric-slider-range").slider({ range: true, min: 0, max: "{{ page_obj.paginator.count }}", slide: function (event, ui) { $("#" + $(this).parent().attr("id") + "_min").val(ui.values[0]); $("#" + $(this).parent().attr("id") + "_max").val(ui.values[1]); $("#" + $(this).parent().attr("id") + "_text").text(ui.values[0] + ' - ' + ui.values[1]); }, create: function (event, ui) { $(this).slider("option", 'min', $(this).parent().data("range_min")); $(this).slider("option", 'max', $(this).parent().data("range_max")); $(this).slider("option", 'values', [$(this).parent().data("cur_min"), $(this).parent().data("cur_max")]); } }); $("#" + $(".numeric-slider").attr("id") + "_min").val($(".numeric-slider").data("cur_min")); $("#" + $(".numeric-slider").attr("id") + "_max").val($(".numeric-slider").data("cur_max")); $("#" + $(".numeric-slider").attr("id") + "_text").text(ui.values[0] + ' - ' + ui.values[1]); }); </script> def index(request): headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36", "Accept-Encoding": "*", "Connection": "keep-alive" } url = "https://www.hetzner.com/a_hz_serverboerse/live_data.json" response = requests.get(url, headers=headers) data = response.json()['server'] p = Paginator(data, 20) pn = request.GET.get('page') page_obj = p.get_page(pn) context … -
How to have a array inside an object in django rest framework api
I want to create this kind of API Django: { question_no: "1", question: "How many sides are equal in a scalene triangle?", options: [ { answer_options: "3", selected: false, isCorrect: true }, { answer_options: "2", selected: false, isCorrect: true }, { answer_options: "0", selected: false, isCorrect: true }, { answer_options: "1", selected: false, isCorrect: true }, ], }, but I don't know how can I add the options array in my API in the Django rest framework. this is the model that I have created so far but it only contains question_no and question: class quiz(models.Model): question_no = models.IntegerField() question = models.CharField(max_length=400) how can I add the options array in my model? -
How can I prevent Wagtail richtext editor from creating autolists?
Is there a way to prevent Wagtail's richtext editor from creating autolists when a line starts with 1.? In some languages dates are written in this format: 1. february 2022. If you write a date in this format in the beginning of a line the richtext's autolist feature formats this as a numbered list. What would be a good way to disable this behaviour?