Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-import-export | issue in importing data to database | ValueError: Field 'id' expected a number but got ''
I am using Django-import-export for importing data but facing an error given below. Code settings i tried to import data to postgresql database by django-import-export class MemberResource(resources.ModelResource): Brand=Field() class Meta: model = model fields=('id','title','Model_code','Chipset','chipset_description','image','Brand','Cat') export_order=('id','title','Model_code','Chipset','chipset_description','image','Brand','Cat') def dehydrate_Brand(self, obj): return str(obj.Brand.title) class modelAdmin(ImportExportModelAdmin): resource_class = MemberResource list_display=['id','title','Model_code','Chipset','chipset_description','Brand','categories'] search_fields = ['title','Model_code','Chipset',] fields=('title','Model_code','Chipset','chipset_description','image','Brand','Cat') admin.site.register(model,modelAdmin) and got below error also attached the image where i exported the data from app and then edited the same and tried to import and stuck with below error. [Line number: 1 - Field 'id' expected a number but got ''. 2, f9, sd, gf, kjkj, images/sample_3pahsfV.jfif, 1, 1 Traceback (most recent call last): File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 187, in _get_ rel_obj = self.field.get_cached_value(instance) File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\fields\mixins.py", line 15, in get_cached_value return instance._state.fields_cache\[cache_name\] KeyError: 'Brand' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\django\db\models\fields\_init_.py", line 1988, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: '' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\import_export\resources.py", line 707, in import_row diff = self.get_diff_class()(self, original, new) File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\import_export\resources.py", line 241, in _init_ self.left = self._export_resource_fields(resource, instance) File "C:\Users\gsminfinity\Desktop\Master\venv\lib\site-packages\import_export\resources.py", line 262, in _export_resource_fields return \[resource.export_field(f, … -
submit multiple forms in django using custom html form
I have custom forms in the page suprated across the page here is my first form <form name="profile_image" class="edit-phto" method="POST" enctype="multipart/form-data"> <i class="fa fa-camera-retro"></i> <label class="fileContainer"> Edit Display Photo <input name="profile_image" value="" type="file" /> </label> </form> for profile picture and i have another form for cover picture <form name="cover_image" class="edit-phto" enctype="multipart/form-data"> <i class="fa fa-camera-retro"></i> <label class="fileContainer"> Edit Cover Photo <input name="cover_image" type="file" /> </label> </form> and another form for data :) <form method="post" id="infoform" enctype="multipart/form-data"> {% csrf_token %} . . . . <div class="submit-btns"> <button type="button" class="mtr-btn"><span>Cancel</span></button> <button type="submit" class="mtr-btn" name="update"><span> Update</span></button> </div> and i have a form for search <div class="searched"> <form method="post" class="form-search"> <input type="text" placeholder="Search Friend"> <button data-ripple><i class="ti-search"></i></button> </form> </div> i just want to submit the 2 images forms and info forms when i click update button is there a way to do sachthing in django without using form.as_p and stuff like that -
Best Django Analytic service or how do i implement a good analytic dashboard
Im new to Django and im trying to build a analytic dashboard for my Django e-commerce project that tracks income, expenses and popular items(items with high demand) and I've been surfing but I cant find how to do it. If anyone has any service that they recommend or any tips on how to implement it ill appreciate it -
Why three methods(get,put,delete) are activated for each of my endpoints? Django Rest Framework
Why three methods(get,put,delete) are activated for each of my endpoints? Django Rest Framework -
django how can i a selected field, as label render
Im create with: class FooForm(forms.ModelForm): class Meta: model = foo fields = '__all__' a auto form of the model. this works fine. When i now render the fields with: {% for field in formfields %} {{ field}} {% endfor %} create me this a field for the foreignkey, like a selectfield: <select name="foo" required id="id_foo"> <option value="">---------</option> <option value="1">A</option> <option value="2" selected>B</option> <option value="3">C</option> <option value="4">D</option> I want but like to display only the selected option like a label: A -
IntelliJ IDEA auto import doewn't work for Python
I have using IntelliJ IDEA for php developement and it works without a issue. I have just started doing some Django coding and I encountered this issue where autocomplete doesn't work for imports. I'm using Python 3.9 with Django 4.0.6 and I use pipenv for virtual environment. I'm trying to do some basic imports like importing HttpResponse from django.http. I expect the IDE to suggest the import as I'm typing (like for php) but it doesn't. for it to work I have to press control+space 2 times and then it shows the suggestions (If I just pres it 1 time it says "No suggestions") or I can type everything then press option+return and it suggests to import it then. Auto Import setting for python is like this: Code Completion setting doesn't have a Python section but the general area is set up like this: Project setting seems to be correct and does have the django module: and this is my .iml file in the .idea folder: <?xml version="1.0" encoding="UTF-8"?> <module type="PYTHON_MODULE" version="4"> <component name="FacetManager"> <facet type="django" name="Django"> <configuration> <option name="rootFolder" value="$MODULE_DIR$" /> <option name="settingsModule" value="django_app/settings.py" /> <option name="manageScript" value="manage.py" /> <option name="environment" value="&lt;map/&gt;" /> <option name="doNotUseTestRunner" value="false" /> <option name="trackFilePattern" … -
Before Sving the page Show an Alert Message Django Script
I am trying to create an alert message before saving the page, i tried to it Django Forms , But did not worked def clean(self): cleaned_data = super(CountryForm, self).clean() cc_myself = cleaned_data.get("registrations") subject = cleaned_data.get("calendar") if cc_myself and subject: if "help" not in subject: raise forms.ValidationError( "You can edit the values" ) -
How to properly catch POST request in a Django serializer when using the JSON Web token authentication?
I customized the AUTH_USER_MODEL variable in settings.py to implement JSON Web Token authentication in Django, and everything works perfectly to login as superuser in the admin section. However, when I try to register a new user with the REST API, the line request.data.get('user', {}) in the serializer returns an empty dictionary, so I need to convert the object of type QueryDict into a Dict. Then I need to unlist the dictionary's values to finally have valid data. I'm afraid there is something wrong in my code, what is the proper way to do that ? I followed the tutorial from Thinkster here. views.py from rest_framework import status from rest_framework.permissions import AllowAny from rest_framework.response import Response from rest_framework.views import APIView from authentication.serializers import RegistrationSerializer class RegistrationAPIView(APIView): permission_classes = (AllowAny,) serializer_class = RegistrationSerializer def post(self, request): # user = request.data.get('user', {}) # <- returns {} user = dict(request.data) user = {k:v[0] for k,v in user.items()} serializer = self.serializer_class(data=user) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) settings.py AUTH_USER_MODEL = 'authentication.User' AUTHENTICATION_BACKENDS = [ 'graphql_jwt.backends.JSONWebTokenBackend', 'django.contrib.auth.backends.ModelBackend', ] GRAPHQL_JWT = { "JWT_ALLOW_ARGUMENT": True, } REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'authentication.backends.JWTAuthentication', ] } -
How do I view movies in descending order of average score? django
What we want to achieve. I want to display the score (stars) of a movie in descending order. Present condition The tmdb API is used to retrieve movie information. And the model movie and TV have only ID and stars(score). From here, only those with stars are returned to html. I want to ask a question. And if score is selected, how can I make it appear in descending score order? data = requests.get (f "https://api.themoviedb.org/3/tv/{tv_id}?api_key={TMDB_API_KEY}&language=en-US"). Now you can get the information of tv. def index(request): movie = reversed(Movie.objects.order_by('stars')) tv = reversed(TV.objects.order_by('stars')) context = { "movie": movie, "tv" : tv, } return render(request, 'Movie/index.html', context) class Movie(models.Model): id = models.CharField(primary_key=True, editable=False, validators=[alphanumeric],max_length = 9999) stars = models.FloatField( blank=False, null=False, default=0, validators=[MinValueValidator(0.0), MaxValueValidator(10.0)] ) def get_comments(self): return Comment_movie.objects.filter(movie_id=self.id) def average_stars(self): comments = self.get_comments() n_comments = comments.count() if n_comments: self.stars = sum([comment.stars for comment in comments]) / n_comments else: self.stars = 0 return self.stars class TV(models.Model): id = models.CharField(primary_key=True, editable=False, validators=[alphanumeric],max_length = 9999) stars = models.FloatField( blank=False, null=False, default=0, validators=[MinValueValidator(0.0), MaxValueValidator(10.0)] ) def get_comments(self): return Comment_tv.objects.filter(tv_id=self.id) def average_stars(self): comments = self.get_comments() n_comments = comments.count() if n_comments: self.stars = sum([comment.stars for comment in comments]) / n_comments else: self.stars = 0 return self.stars class … -
Django: How to save javascript auto-increment to django database?
I am incrementing a value from my database evey 3.5 sec using javascript, but the value that i am incremeting is coming dynamically from the database, now i want to save the newly incremented value to the database as the increment keeps going, i don't know how to achieve this using django and javascript. When i refresh the page, the value resets to the default value that i have in my database and doesn't update the value with the new increments <span id="generated">{{total_points}}</span> <!-- This is the js doing the increment function --> <script> var i = {{total_points}}; function increment() { i++; document.getElementById('generated').innerHTML = `₦` + Number(i).toLocaleString('en') + `.00`; } setInterval('increment()', 3140); </script> how do i save the new increments to the database? Do i need to provide my models.py? -
How to make divisions go on a new line? html/css
So, I want maximum of 3 div's per row, so when I use "for" loop after 3 instances it would automatically go to a new line. I have very little knowledge in js, so it'll be better if you can suggest me something not connected with it. Thank you in advance. (Making this template for my first django project). .main-section{ background: white; text-align: center; border: solid 1px #D1BEA8; } .book-list-main{ display: table; table-layout: fixed; border-spacing: 30px; } .single-book{ display: table-cell; width: 310px; height: 400px; margin: 0 20px 20px 10px; grid-column-start: 1; border: solid 1px #D1BEA8; height: fit-content; } .img-description-container{ display: flex; } .single-book h1{ font-size: 20px; } .img-description-container img{ max-width: 180px; max-height: 240px; float: left; } .img-description-container p{ float: right; font-size: 12px; overflow-y: scroll; margin-top: 50px; } .author-display{ display: flex; flex-direction: column; } .author-display span{ font-size: 14px; margin-top: 30px; background-color: #f1efe5; } .votes-total { position: relative; } .votes-total:before { content: attr(data-hover); visibility: hidden; opacity: 0; width: 60px; color: black; background-color: aliceblue; text-align: center; border-radius: 5px; padding: 5px 0; position: absolute; font-size: 11px; z-index: 1; left: 0; top: -110%; } .votes-total:hover:before { opacity: 1; visibility: visible; } .single-book-footer{ margin-top: 15px; margin-left: 17px; display: flex; flex-direction: row; } .single-book-footer button{ height: 30px; … -
CSS file references a file which could not be found. (Fieldsets forms and Heroku)
I am using fieldsets for my django forms. Everything works fine on local. I wanted to uploaded onto Heroku and started running into problem. When running "python manage.py collectstatic", I am getting the following error: The CSS file 'forms_fieldset\css\main.css' references a file which could not be found: forms_fieldset/img/sorting-icons.svg The message is correct. The file forms_fieldset/img/sorting-icons.svg is not mentioned in main.css. I suppose there is two questions: How does it know a file does not exist, if it actually not mentioned anywhere? How and where can I add this file? Below is my settings.py, just in case someone wants to look at it: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "crispy_forms", 'main.apps.MainConfig', 'register.apps.RegisterConfig', 'import_export', 'forms_fieldset', ] ... STATIC_URL = 'static/' #IMAGE STUFF# MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') #Staticfiles_storage to make it compatible with Heroku SATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' #storing static files VENV_PATH = os.path.dirname(BASE_DIR) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"),) -
Customizing authentication backend for multi users in Django
So my question is that you have a custom user 'Account' and I'm trying to use Loginview but with only one specific backend but the class does not care about the value passed. from django.contrib.auth import views as auth_views from .lists import ProjectCreateView , ProjectUpdateView , ProjectDeleteView class ClientLogin(auth_views.Loginview): def form_valid(self, form): """Security check complete. Log the user in.""" auth_login(self.request, form.get_user(),'CREA.models.ClientBackend') return HttpResponseRedirect(self.get_success_url()) urlpatterns = [ path('', ClientLogin.as_view(template_name='authentification/client_login.html', redirect_authenticated_user=True,next_page='client-home'), name='client-log-in'), NB: note that the backend works fine if it's the only one specified in the settings but other than that the loginview use all backends one by one, and yes I know that this is the default behaviour but then whats the point of this variable in auth_login here is the buld in function in django : def login(request, user, backend=None): """ Persist a user id and a backend in the request. This way a user doesn't have to reauthenticate on every request. Note that data set during the anonymous session is retained when the user logs in. """ session_auth_hash = "" if user is None: user = request.user if hasattr(user, "get_session_auth_hash"): session_auth_hash = user.get_session_auth_hash() if SESSION_KEY in request.session: if _get_user_session_key(request) != user.pk or ( session_auth_hash and not constant_time_compare( request.session.get(HASH_SESSION_KEY, … -
django import_export | data not exported from database
I am using Django-import_export for exporting data. I have used the code given below that's not working correctly. It exported only dehydrated data instead of given fields. class MemberResource(resources.ModelResource): Brand=Field() class meta: model = model fields=('title','Brand') def dehydrate_Brand(self, obj): return str(obj.Brand.title) class modelAdmin(ImportExportModelAdmin): resource_class = MemberResource list_display=['title','Model_code','Chipset','chipset_description','Brand','categories'] search_fields = ['title','Model_code','Chipset',] fields=('title','Model_code','Chipset','chipset_description','image','Brand','Cat') admin.site.register(model,modelAdmin) -
in decorator assert not existing_data, "swagger_auto_schema applied twice to method"
I have added three input fields as headers but coming swagger_auto_schema applied twice to method issue and other one when I'm adding one swagger_auto_schema with given header input field than working fine where as when I'm adding three swagger_auto_schema with adding thier object than getting this error This is my code from rest_framework.generics import GenericAPIView from drf_yasg.utils import swagger_auto_schema from drf_yasg import openapi class ProductDataView(GenericAPIView): serializer_class = ProductSerializer permission_classes = (IsValidConsumer,) categories = openapi.Parameter('categories', in_=openapi.IN_HEADER, description='categories', type=openapi.TYPE_STRING, required=True) productName = openapi.Parameter('product_name', in_=openapi.IN_HEADER, description='product_name', type=openapi.TYPE_STRING) CustomerName = openapi.Parameter('customer_name', in_=openapi.IN_HEADER, description='customer_name', type=openapi.TYPE_STRING) @swagger_auto_schema(manual_parameters=[productName]) @swagger_auto_schema(manual_parameters=[categories]) @swagger_auto_schema(manual_parameters=[CustomerName]) -
how to pass 2 pks of different models in the same url django
how do i add primary keys of 2 different models of post model and comment model in the same url of editing comments when im adding 2 int pks in the same url it shows an error and when im giving 1 custom name then it doesnt work views.py class EditCommentView(UpdateView): model = Comment form_class = EditCommentForm template_name = "edit_comment.html" urls.py urlpatterns = [ path("post/<int:pk>/comments/", login_required(CommentsView.as_view(), login_url='signin'), name="comments"), path("post/<int:pk>/comments/add/", login_required(AddCommentView.as_view(), login_url='signin'), name="add-comment"), path("post/<int:pk>/comments/<int:pk>/edit/", login_required(EditCommentView.as_view(), login_url='signin'), name="edit-comment"), ] template {% extends "base.html" %} {% block content %} <section class="text-gray-600 body-font overflow-hidden"> <div class="container px-5 py-24 mx-auto"> <div class="flex flex-col text-center w-full mb-12"> <h1 class="sm:text-3xl text-2xl font-medium title-font mb-4 text-gray-900">Comments</h1> <p class="lg:w-2/3 mx-auto leading-relaxed text-base"> <a class="text-indigo-500 inline-flex items-center mt-4" href="{% url 'add-comment' post_id %}">Add Comment </a> </p> </div> <div class="-my-8 divide-y-2 divide-gray-100"> {% for comment in object_list %} <div class="py-8 flex flex-wrap md:flex-nowrap"> <div class="md:w-64 md:mb-0 mb-6 flex-shrink-0 flex flex-col"> <!-- <span class="font-semibold title-font text-gray-700">CATEGORY</span> --> <span class="mt-1 text-gray-500 text-sm">{{comment.date_created}}</span> </div> <div class="md:flex-grow"> <h2 class="text-2xl font-medium text-gray-900 title-font mb-2">{{comment.user.username}}</h2> <p class="leading-relaxed">{{comment.body}}</p> <a class="text-indigo-500 inline-flex items-center mt-4" href="{% url 'edit-comment' post_id comment.id %}"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-pencil-square" viewBox="0 0 16 16"> <path d="M15.502 1.94a.5.5 0 0 1 0 .706L14.459 3.69l-2-2L13.502.646a.5.5 … -
Show an Alert Message before saving the page Django
I am trying to create an alert message before saving the page, i tried to it Django Forms , But did not worked def clean(self): cleaned_data = super(CountryForm, self).clean() cc_myself = cleaned_data.get("registrations") subject = cleaned_data.get("calendar") if cc_myself and subject: # Only do something if both fields are valid so far. if "help" not in subject: raise forms.ValidationError( "You can edit the values" ) -
DRF Add multiple annotated fields to nested serializer
In my queryset i have few annotate fields. I want group those fields to nested serializer. For example views.py class PostViewSet(viewsets.ModelViewSet): queryset = Post.objects.all().prefetch_related( Prefetch('comments', queryset=Comment.objects.filter(parent__isnull=True).order_by('-pub_date') .annotate(likes=Count('votes', filter=Q(votes__choice=True)), dislikes=Count('votes', filter=Q(votes__choice=False))))) So there is two additional fields 'likes', 'dislikes' serializers.py class CommentVoteSerializer(serializers.Serializer): likes = serializers.IntegerField(source='comments.likes') dislikes = serializers.IntegerField(source='comments.dislikes') class Meta: fields = ['likes', 'dislikes'] class CommentSerializer(serializers.ModelSerializer): rating = CommentLikesSerializer(read_only=True, many=True) class Meta: model = Comment fields = ['id', 'text', 'pub_date', 'rating'] I tried different ways but can't understand how to fix it. Thanks for help -
convart raw sql to django query
I want to convert qs = Category.objects.raw('SELECT y.id,y.name,y.parent_id FROM core_category y INNER JOIN (SELECT name,parent_id, COUNT(*) AS CountOf FROM core_category GROUP BY name,parent_id HAVING COUNT(*)>1 ) dt ON y.name=dt.name AND y.parent_id=dt.parent_id') this raw sql to django sql query -
spotify api "player/currently-playing" enpoint is not return currently playing song data
I am trying to get data about a song playing on one of my devices from the spotify API. I have created a view that fetches data from the API and part of it looks like this: class Song(viewsets.ModelViewSets): .... room_code = request.data['room_code'] room = Room.objects.filter(code=room_code)[0] host = room.host endpoint = 'player/currently-playing' response = execute_spotify_api_request(host, endpoint) item = response.get('item') duration = item.get('duration_ms') progress = response.get('progress_ms') album_cover = item.get('album').get('images')[0].get('url') return Response(response, status=status.HTTP_200_OK) The execute_spotify_api_request(host, endpoint) is a utility function and it looks like this: def execute_spotify_api_request(session_id, endpoint, post_=False, put_=False): tokens = get_user_tokens(session_id) headers = {'Content-Type': 'application/json', 'Authorization': "Bearer " + tokens.access_token} if post_: post(BASE_URL + endpoint, headers=headers) if put_: post(BASE_URL + endpoint, headers=headers) response = get(BASE_URL, {}, headers=headers) try: return response.json() except: return {'error': 'Could not retrieve a response'} The full url from which im fetching is ""https://api.spotify.com/v1/me/player/currently-playing" The problem is with the response that im getting from the API, the response is not an error but data that im not expecting to get. Im getting a response that looks like this: response = { "display_name": "Tanatswamanyakara", "external_urls": { "spotify": "https://open.spotify.com/user/dlnsysel6bndktbvduz6cl79w" }, "followers": { "href": null, "total": 0 }, "href": "https://api.spotify.com/v1/users/dlnsysel6bndktbvduz6cl79w", "id": "dlnsysel6bndktbvduz6cl79w", "images": [], "type": "user", "uri": "spotify:user:dlnsysel6bndktbvduz6cl79w" } I … -
Restricting User to have one one-to-one relationship with any one of the given models Django
I am having two model classes named as Leader and Member, both have a OnetoOne relationship with User, as you can see below: from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.DO_NOTHING) # Abstract model class for common fields in Leader and Member class Meta: abstract = True class Leader(Profile): # attributes # def save(self) -> None: # if Member.objects.filter(user=self.user).first() == None: # return super().save() # else: # raise ValidationError("User is already a member, migrate it to make it leader.") class Member(Profile): # attributes But if a user is already having a relation with anyone, among both of them, then it should not be allowed to have a relation with the other one. For example: If a user1 is referenced by Leader model, then it is not allowed to be referenced by Member model, if needed there should be a process by which we can remove and add user from Leader model to Member model, i.e. transferring Profile abstract model data from Leader model to Member model and receiving remaining data manually or vica versa. By searching over the internet, I got to know that to solve this there is a way of raising ValidationError, … -
Images disappear when Django debug=False
When preparing to deploy my Django website to production, of course I turn the "debug" flag to "false" in my settings file. For some reason, all my images stop appearing. Here is my call to the image(s) in my template(s): <div id='photo1'> <img src="{% static 'app/image.png' %}" alt="Image Text"> </div> Appreciate suggestions for formatting my image links so they survive transition to production! -
Write to CSV file with manytomany field in Django
I have a model that includes two fields many to many from the model of plants and I would like to write in a CSV file, thanks to the library panda, the name of the plants and the associated plants of the model. Here is function to write a CSV file but I don't know how to write the fields in many to many with the name of the plants : class UploadLinkPlantData(generics.CreateAPIView): serializer_class = FileUploadSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) file = serializer.validated_data['file'] reader = pd.read_csv(file) for _, row in reader.iterrows(): LnkPlantPlant.objects.update_or_create( custom_id=row['Custom Id'], defaults={ "custom_id": row['Custom Id'], "link": row['Link'], "description": row['Description'] }) return Response({"status": "Succès : plante(s) crée(s) ou mise(s) à jour."}, status.HTTP_201_CREATED) class LnkPlantPlant(models.Model): class MAGNET_CHOICES(models.TextChoices): NONE = None IDEAL = 'ideal', GOOD = 'good', MEDIOCRE = 'mediocre', BAD = 'bad' custom_id = models.IntegerField(primary_key=True, unique=True) plant = models.ManyToManyField('perma_plants.Plant', related_name='%(class)s_plant') plant_associated = models.ManyToManyField('perma_plants.Plant', related_name='%(class)s_plant_associated') link = models.CharField(max_length=10, choices=MAGNET_CHOICES.choices, default=MAGNET_CHOICES.NONE, blank=True, null=True) description = RichTextField(max_length=255, blank=True, null=True) Here is Plant model : class Plant(models.Model): custom_id = models.IntegerField(primary_key=True, unique=True) name = models.CharField(max_length=150) def __str__(self): return self.name -
Displaying data using datatbales through django rest framework
https://www.youtube.com/watch?v=ntH6Fb9Rdkw I've followed this tutorial on how to fetch data to datatables using django(that person used core django while i wanna fetch and display data through django rest framework ) this is how my json structure is "results": [ { "book": "1", "author": "1", "status": 1 }, while on the frontend #datatables script part <script> $(document).ready(function () { $('#data').DataTable({ "processing": true, "serverSide": true, "ajax": { "type": "GET", "url": 'http://localhost:8000/api/books/', data: function ( data ) { console.log(data) } }, "columns":[ {"results":"book"}, {"results":"author"}, {"results":"status"} ] }); }); </script> #html part <table id="data"class="table table-striped table-hover"> <thead> <tr> <th>Books</th> <th>Author</th> <th>Status</th> </tr> </thead> where i could get a 200 request in the console #in console results: [{book: "1", author: "1", status: 1},…] 0: {book: "1", author: "1", status: 1} yet the table isnt fetching any data and i dont understand what exactly is wrong -
Responsive Navbar Link is not working on mobile device
I developed my first website using django. It works perfect on desktop, but on mobile device the category submenu links are not working. When clicked they act like I clicked on white space and close the navbar. Note: the Intital links work on mobile too. The children of the categories are not working. I though about z-index but the parent links are working. Here are the codes: <div id="responsive-nav"> <!-- category nav --> {% if page %} <div class="category-nav"> {% else %} <div class="category-nav show-on-click"> {% endif %} <span class="category-header">{% trans "Categories" %} <i class="fa fa-list"></i></span> {% load myapptags %} {% categorylist as category %} {% load mptt_tags %} <ul class="category-list"> {% recursetree category %} <li class="dropdown side-dropdown"> <a href="{% url 'category_products' node.id node.slug %}" class="dropdown-toggle" {% if not node.is_leaf_node %} data-toggle="dropdown" aria-expanded="true" {% endif %}>{{ node.title }} <i class="fa fa-angle-right"></i></a> <div class="custom-menu"> {% if not node.is_leaf_node %} <ul class="children"> {{ children }} </ul> {% endif %} </div> </li> {% endrecursetree %} </ul> </div> my apptag @register.simple_tag def categorylist(): return Category.objects.all() css of mobile @media only screen and (max-width: 991px) { #responsive-nav { position: fixed; left: 0; top: 0; bottom: 0; max-width: 270px; width: 0%; overflow: hidden; background-color: #FFF; -webkit-transform: …