Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
PostGIS geography does not support the "~=" function/operator
I am trying to save point field in the database via update_or_create method but it is giving me this error. My function to save data: for city in cities_data: obj, created = models.City.objects.update_or_create( name = city["name"], country = city["country"], state = city["state"], point = Point( float(city["longitude"]), float(city["latitude"]) ), radius = city["radius"], is_curated = city["is_curated"], is_metro_city = city["is_metro_city"] ) obj.save() Model: class City(models.Model): name = models.CharField(max_length=50) country = models.CharField(max_length=50) state = models.CharField(max_length=50) point = gis_models.PointField(geography=True, null=True) is_metro_city = models.BooleanField(default=False) is_curated = models.BooleanField(default=False) radius = models.IntegerField(null=True) when I try to run this I get this error: ValueError: PostGIS geography does not support the "~=" function/operator. I want to know why I am getting this error, I did not find any useful information related to this. Thanks in Advance. -
How to save the position of draggable elements?
Hello, I am making a web application in django, what it allows you to do is drag elements on the page, what I want to do is save the position of these elements so that when the page is reloaded the elements remain in the same position in which they left, is there any way to save the position? This is my javascript to drag elements. <script src="http://threedubmedia.com/inc/js/jquery-1.7.2.js"></script> <script src="http://threedubmedia.com/inc/js/jquery.event.drag-2.2.js"></script> <script type="text/javascript"> jQuery(function ($) { $('.drag') .click(function () { $(this).toggleClass("selected"); }) .drag("init", function () { if ($(this).is('.selected')) return $('.selected'); }) .drag(function (ev, dd) { $(this).css({ top: dd.offsetY, left: dd.offsetX }); }); }); And this is the element or elements that are dragged, the number of elements is variable since it is conditioned by a database. <div class="drag"> <span class="dot" title="{{ device.device_name }}" style="background-color: #197f32"><br/><b><p style="color: #ce3830;"> {{ device.device_name }}</p></b></span> </div> -
how can i show query id from div to an other div whene click add to cart, in same page with ajax and django?
Hi, I would like to finish a university project, but I found a big problem, how to query the same page using ajax without reloading the page** like this website: https://cairogourmet.com/menu model.py class Plat_a_manger(models.Model): user_plat = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, max_length=200, on_delete=models.CASCADE) title_plat = models.CharField('العنوان', max_length=9500) price = models.DecimalField(max_digits=200, decimal_places=3, default=0.00) image_plat = models.ImageField('صورة مناسبة', upload_to = 'Images_Plat') def __str__(self): return self.title_plat views.py from django.shortcuts import render from andalous.models import Category, Plat_a_manger def product_list(request): cat = Category.objects.all().order_by('id') plat = Plat_a_manger.objects.all().order_by('id') ctx = { 'cat': cat, 'plat': plat, } return render(request, 'home/menu.html', ctx) urls.py from django.contrib import admin from django.urls import path from django.conf.urls import url from django.contrib.auth import views as auth_views from .import views app_name="andalous" urlpatterns = [ url(r'^$', views.index, name='index'), url(r'menu/$', views.product_list, name="product_list"), ] -
ModuleNotFoundError: No module named 'apps.news'; 'apps' is not a package
I have a Django project with the following structure: project apps news models.py hose tasks.py Within tasks.py, I have this import from apps.news.models import Company When I try to run tasks.py, I get the following error: ModuleNotFoundError: No module named 'apps.news'; 'apps' is not a package How do I fix this error? I don't understand why this import does not work. -
Python. Poll the my REST service until a response is received
I'am writing restful service with its own database. I have an endpoint (/generate) the answer to which is very long in time. The client cannot wait long for a response from this rest. The following idea came up: Upon request for endpoint '/generate' the client receives a unique key With this key, the client polls the service until the data is ready Аs soon as the data is ready, the client can request it using the same key What framework and how can this be implemented? I hope I've made my point clear -
ValueError: Cannot assign "<User: username>": "MessageModel.user_name" must be a "Room" instance
I have ita MessageModel which have a field user_name which is a instance of Room model. i want to save all the messages of current user inline but when i try to save username which is instance of Room model...an error occured like--> ValueError: Cannot assign "<User: username>": "MessageModel.user_name" must be a "Room" instance. I have a another model DateTimeField which has the following field datecreated and date_modified. models.py--> class Room(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='owner', null=True) def __str__(self): return str(self.user.username) class MessageModel(DateTimeModel): user_name = models.ForeignKey(Room, null=True, blank=True, on_delete=models.SET_NULL) user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name = 'sender', on_delete=models.CASCADE, null=True) message = models.TextField('body') recipients = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='recipients') class Meta: ordering = ['-id'] forms.py--> class MessageModelInline(admin.TabularInline): model = MessageModel class RoomAdmin(admin.ModelAdmin): inlines = [MessageModelInline] admin.site.register(Room, RoomAdmin) @database_sync_to_async def save_message_to_db(self,username, message): user_name = self.user_name print(type(user_name)) # <class 'django.contrib.auth.models.User'> return MessageModel.objects.create(user_name=user_name, user=username, message=message) any solution will be highly appreciated. ThankYou -
ManyToManyField is showing error while migrate in django
While I was doing the coding I changed one field to "ManyToManyField". When I try to migrate it is showing the following error. Models.py class Department(models.Model): Dept_No = models.CharField(primary_key=True, max_length=6) Dept_Name = models.CharField(unique=True, max_length=20) Dept_Manager = models.OneToOneField('Employee_Detail', models.DO_NOTHING, limit_choices_to={'Position': 'Manager'}) def __str__(self): return self.Dept_No class Employee_Detail(models.Model): Employee_ID = models.CharField(primary_key=True, max_length=6) Employee_Name = models.CharField(unique=True, max_length=30) Primary_Phone = models.IntegerField(unique=True, max_length=10) Secondary_Phone = models.IntegerField(unique=True, max_length=10) p = ( ("Manager","Manager"),("Supervisor","Supervisor"),("Employee","Employee") ) Position = models.CharField(max_length=15, choices= p, default="Employee") Address = models.TextField(max_length=500) Email = models.EmailField(max_length=50, unique=True) def __str__(self): return str(self.Employee_Name) class Leave(models.Model): Employee_Name = models.ManyToManyField(Employee_Detail,default=" ") Dept_Name = models.ForeignKey('Department', models.DO_NOTHING) l = ( ("Paid","Paid"),("Non-Paid","Non-Paid") ) Leave_Type = models.CharField(max_length=10, choices= l, default="Non-Paid") Start_Date = models.DateField() End_Date = models.DateField(null=True, blank = True) Reason = models.CharField(max_length=200) s = ( ("Accepted","Accepted"),("Pending","Pending"),("Canceled","Canceled") ) Status = models.CharField(max_length=10, choices= s, default="Pending") def __str__(self): return str(self.Employee_Name) Admin.py class LeaveAdmin(admin.ModelAdmin): list_display = ["Employee_Name","Dept_Name","Leave_Type","Start_Date","End_Date","Reason","Status"] search_fields = ["Employee_Name__Employee_Name","Dept_Name__Dept_Name","Leave_Type"] list_filter = ["Employee_Name","Dept_Name","Status"] admin.site.register(Leave, LeaveAdmin) How to prevent this error and how to create ManyToManyField without error? -
Adding Data to Request in Django REST Framework in Authentication Class
Suppose I have the following Authentication class in DRF. If the request is authenticated, then I need some additional data in the request object. Say, REQUIRED_DATA is that variable. class MyAuthClass(BaseAuthentication): def authenticate(self, request): # suppose is_authenticated_request and authenticated_user are methods # which return the responses as described by their name if is_authenticated_request(request): user = authenticated_user(request) request.REQUIRED_DATA = some_variable_of_any_type return (user, None) raise exception.AuthenticationFailed(_('Authentication failed.')) Here is how I used it in the viewset. class MyViewSet(viewsets.GenericViewSet): authentication_classes = [MyAuthClass] permission_classes = [permissions.IsAuthenticated] def create(self, request, *args, **kwargs): ############# # ......... # request.REQUIRED_DATA # using variable # ......... # ############# Am I going right? I need this variable after the request is authenticated. Is their a better way to do this? Middleware is one but Middleware runs for each request, I need for this viewset only. -
Git Heroku Django - Git pull heroku master not pulling rolled back version?
Within the Heroku admin portal I rolled back to a previous version of my application. I would like this rolled back version to be my heroku master. However when I do git pull heroku master it pulls the last release I did git push heroku master from on my local machine, not the rolled back version. How can I update my rolled back version to be the heroku master in heroku? -
How to unittest Django Rest Framework endpoint with XML?
I've got an endpoint which I built with Django Rest Framework. It works great when I test it with something like Postman, but my unit tests fail. When I test my json endpoints I always post Python dicts instead of json strings, like this: response = self.client.post('/json-endpoint/', {'a': 1}, format='json') When I test the xml endpoint I tried to post a raw xml string like this: response = self.client.post('/xml-endpoint/', '<?xml version="1.0" encoding="UTF-8" ?><myDataStructure></myDataStructure>', format='xml') But this doesn't work. In my Viewset I override the create() method, and in there, my xml somehow seems to be "packaged" into another xml. If I print out request.body in the create() method I see this: b'<?xml version="1.0" encoding="utf-8"?>\n<root>&lt;?xml version="1.0" encoding="UTF-8" ?&gt;\n&lt;myDataStructure&gt;\n etc.. As you can see my xml is somehow encoded and then packed into another <?xml version="1.0" encoding="utf-8"?>\n<root>. Does anybody know how I can properly provide the xml when I write unit tests for the xml endpoint? All tips are welcome! -
django modelmanager queryset not returning page
I've been following the guidance in Two Scoops of Django and applying this to a re-write of my own apps. I have a model called Bookings with a ModelManager which filters to select only future dated bookings. An extract is below but the relevant field is start_date. guest_status = models.IntegerField('Guest status', choices=GuestStatus.choices, default=0) ack_date = models.DateField(verbose_name='Date acknowledged') start_date = models.DateField(verbose_name='Start date') end_date = models.DateField(verbose_name='End date') dep_recd = models.DateField(null=True, blank=True, verbose_name='Deposit received') bal_amount = models.IntegerField('Balance due', default=0) dep_amount = models.IntegerField('Deposit amount', default=0) sec_recd = models.IntegerField('Security deposit', choices=SecurityStatus.choices, default=0) bal_recd = models.DateField(null=True, blank=True, verbose_name='Balance received') keys_sent = models.DateField(null=True, blank=True, verbose_name='Date keys sent') sec_retn = models.DateField(null=True, blank=True, verbose_name='Security deposit returned') booking_status = models.IntegerField('Status', choices=BookingStatus.choices, default=0) booking_notes = models.TextField(blank=True, verbose_name='Notes') bkd_child = models.IntegerField('Children', default=0) bkd_adult = models.IntegerField('Adults', default=2) guest_one = models.CharField(blank=True, verbose_name='Guest 1', max_length=30) guest_two = models.CharField(blank=True, verbose_name='Guest 2', max_length=30) guest_three = models.CharField(blank=True, verbose_name='Guest 3', max_length=30) guest_three = models.CharField(blank=True, verbose_name='Guest 3', max_length=30) slug = AutoSlugField(unique=True, populate_from=get_populate_from) num_nights = models.IntegerField('Nights', default=0) objects = FutureBookings() The ModelManager appears before the Bookings model: class FutureBookings(models.Manager): def booked(self): return self.filter(start_date__gte=pendulum.now()) When I test this in shell_plus it works as it should do. When I run the site however I get a 404: Request Method: GET Request URL: http://127.0.0.1:8000/bookings/current/ … -
map widgets page not load in live server it is work in local server
Django-map-widgets page-load in the local server my local server but it is not working in live server my live server here my HTML file {% extends "base.html" %} <HTML> <head> <title>Shop</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> {% load static %} {% block extrahead %} {{ form.media }} <script type="text/javascript"> $(document).on("google_point_map_widget:marker_create", function (e, lat, lng, locationInputElem, mapWrapID) { console.log(locationInputElem); // django widget textarea widget (hidden) console.log(lat, lng); // created marker coordinates console.log(mapWrapID); // map widget wrapper element ID }); $(document).on("google_point_map_widget:marker_change", function (e, lat, lng, locationInputElem, mapWrapID) { console.log(locationInputElem); // django widget textarea widget (hidden) console.log(lat, lng); // changed marker coordinates console.log(mapWrapID); // map widget wrapper element ID }); $(document).on("google_point_map_widget:marker_delete", function (e, lat, lng, locationInputElem, mapWrapID) { console.log(locationInputElem); // django widget textarea widget (hidden) console.log(lat, lng); // deleted marker coordinates console.log(mapWrapID); // map widget wrapper element ID }) </script> {% endblock extrahead %} </head><body> {% block content %} {% include 'CustomerNavbar.html' %} <br> <form method="POST" action="" enctype="multipart/form-data" > {% csrf_token %} {{form.as_p}} <input class="btn btn-primary" type="submit" name="Update Information"> </form> {% endblock content %} </body></html> when I find inspect on live server I see (index):1 Refused to apply style from 'https://vishalbusiness.com/static/css/bootstrap-theme.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, … -
how use setUp in selenium webdriver remote?
I want to use setUp instead of setUpClass in my selenium tests. This code works fine and is able to get the correct host when using setUpClass: @tag('selenium') @override_settings(ALLOWED_HOSTS=['*']) class BaseTestCase(StaticLiveServerTestCase): """ Provides base test class which connects to the Docker container running selenium. """ host = '0.0.0.0' @classmethod def setUpClass(cls): super().setUpClass() cls.host = socket.gethostbyname(socket.gethostname()) cls.selenium = webdriver.Remote( command_executor='http://selenium_hub:4444/wd/hub', desired_capabilities=DesiredCapabilities.CHROME.copy(), ) cls.selenium.implicitly_wait(15) How should I do it if I'm gonna use setUp? @tag('selenium') @override_settings(ALLOWED_HOSTS=['*']) class BaseTestCase(StaticLiveServerTestCase): """ Provides base test class which connects to the Docker container running selenium. """ host = '0.0.0.0' def setUp(self) -> None: super(BaseTestCase, self).setUp() self.selenium = webdriver.Remote( command_executor='http://selenium_hub:4444/wd/hub', desired_capabilities=DesiredCapabilities.CHROME.copy(), ) self.host = socket.gethostbyname(socket.gethostname()) self.selenium.implicitly_wait(15) -
Documentation tool - Search into HTML files from django templates
I am working on a website using django. I have a documentation section with plain HTML files (i.e. not related to the django databases, just text). Those files have been converted from LaTeX to HTML. I would like to add a search bar into my documentation so the user can search a word to get some kind of help, for example by: highlighting the word in the text, returning a list of urls of the pages where the word occur, telling me how many times this word occur in each section of the table of content, ... I've been searching on the web for a while be could not find anything on how I could do this. I would appreciate any help/tips. Thanks in advance. -
Reverse for 'post_list' with keyword arguments '{'pk': 20}' not found. 1 pattern(s) tried: ['$']
I'm getting this NoReverseMatch error with pk 20 even when i have created only one post in the database. It doesn't the list all the posts as it should do and it gives this error. [enter image description here][1] This is the screen shot [1]: https://i.stack.imgur.com/GoqyT.png models.py from django.db import models from django.urls import reverse from django.utils import timezone # Create your models here. class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=100) text = models.TextField() created_on = models.DateTimeField(default=timezone.now) published_on = models.DateTimeField(blank=True, null=True) def publish(self): self.published_on = timezone.now() self.save() def approve_comments(self): return self.comments.filter(approve_comment=True) def get_absolute_url(self): return reverse("post_detail", kwargs={"pk": self.pk}) # def __str__(self): # return self.author def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments') author = models.CharField(max_length=100) text = models.TextField() created_on = models.DateTimeField(default=timezone.now) approve_comment = models.BooleanField(default=False) def approve(self): self.approve_comment = True self.save() def get_absolute_url(self): return reverse("post_list") # def __str__(self): # return self.text def __str__(self): return self.text urls.py from django.urls import path from blog import views urlpatterns = [ path('', views.PostListView.as_view(), name='post_list'), path('post/<int:pk>/', views.PostDetailView.as_view(), name='post_detail'), path('post/new/', views.PostCreateView.as_view(), name='post_new'), path('post/<int:pk>/delete/', views.PostDeleteView.as_view(), name='post_delete'), path('post/<int:pk>/update/', views.UpdatePostView.as_view(), name='post_update'), path('draft/', views.DraftListView.as_view(), name='post_draft_list'), path('post/<int:pk>/publish/', views.PostPublish, name='post_publish'), path('post/<int:pk>/comment/', views.add_comment_to_post, name='comment_new'), path('comment/<int:pk>/approve/', views.comment_approve, name='comment_approve'), path('comment/<int:pk>/remove/', views.remove_comment, name='comment_delete') ] views.py(only the list view) class PostListView(ListView): model = Post … -
how to merge django urls for GET and POST
I need help, I got a path() issue when I was trying route GET/POST request on a single url: When I want to add a server recored, I would do a POST {"serverid":1,"hostname":"test server"} on the url: /api/server/ but sometime I'd like to query the server by serverid, then I had to write another path() mapping for GET: /api/server/<int:serverid>/ Obviously they both can be in one view class/method, I believe this is more duplicated, but how can I merge these two url into one path? Thanks for your help. -
How to set dynamic or any caching in Django+Gunicorn+Nginx?
Ultimately I want my webapp to automatically detect changes in static files and serve the new ones, but even setting a cache policy successfully in Nginx would do at the moment. I tried several approaches: including expires: off;, expires: 1h; in my sites-enabled/projectname file, also including this inside and outside the scope location {...}, none of it worked. I tried to check with curl -I https://mywebsite, but no information about cache policy was returned either times. (I also restarted nginx after each change.) The file: server { listen 443 ssl http2; ssl on; ssl_certificate /home/name/ssl/sitename/certificate.crt; ssl_certificate_key /home/name/ssl/sitename/private.key; server_name sitename; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/name/projectname; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } Currently this is what curl gives back: HTTP/2 405 server: nginx/1.10.3 (Ubuntu) date: Mon, 27 Jul 2020 15:10:26 GMT content-type: text/html; charset=utf-8 content-length: 0 allow: GET x-frame-options: DENY vary: Cookie x-content-type-options: nosniff Any help is much appreciated! -
Django server not running in LAN
I'm trying to access my Django server with my phone in the local network. It used to work fine until my router was changed and now my server can only be accessed from the same maschine, which is weird. I tried the following: Added my private IP (ipconfig > WIFI-3 LAN adapter > ipv4) = 192.168.0.23 to ALLOWED_HOSTS Ran python manage.py 0.0.0.0:8000 Then tried to access the url http://192.168.0.23:8000 from my phone But I get a timeout error and no response. When i access the same URL from my maschine, it works just fine. I also tried running python manage.py runserver 192.168.0.23:8000, but got the same result. I made sure that I was working in the same network. What am I missing here? -
Setting up a Two Tiered User System in Django
I'm pretty new with Django. I'm building my first app using the framework: a simple blog. I want to implement two different types of users: an ordinary user who can only comment on posts, and an admin user who can both comment on posts and create posts. my current set up is as follows: models.py: User = get_user_model() class Author(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) profile_picture = models.ImageField() def __str__(self): return self.user.username right now once logged in a user can do everything. From reading the following documentation: https://docs.djangoproject.com/en/2.2/topics/auth/default/#groups , https://docs.djangoproject.com/en/3.0/topics/auth/customizing/#extending-user . I think the way to do that would be with with different user groups, but like I said I'm new at this. My question is essentially what is the best / simplest configuration I can use to enable a two user system? Also on a side note while reading through the docs I saw a section saying that if you're starting a new project it's highly recommended to set up a custom user model. I didn't do this. I only have two users in the system currently: myself as a super user, and a test user. Can I just delete the test user and then create a custom user class? -
Can I see what is happening in the django admin side?
Is it possible with Django to have an overview of what is happening when I set an object with the admin interface ? Because I want to give ability to an admin to set some objects, then I want that some modifications automatically impact other objects. But I can't find where a the files or where are the functions called by the admin interface. I looked into admin.py but it allows me to filter, exclude or display some fields, no interest for my problem. Have you an idea how to see what is happening in admin side please ? Thank your for reading -
A HTTP 404 with get/static
I got a GET HTTP 404 when I ran my Django page. The goal is to get an arrow showing a dropdown list to log me out when I click on it. I followed the tutorial on https://simpleisbetterthancomplex.com/series/2017/09/25/a-complete-beginners-guide-to-django-part-4.html#displaying-menu-for-authenticated-users It says GET static/js/bootstrap.min.js HTTP/1.1 404 1683 I need to know why I am getting this error. Can anyone show me how to fix this? -
When in uje {% for loop %} in html js doesnt work django
js code in base.html. When i use loop in html first box work but second box doesn't work I add script code this file in side even so doesn't work How i can do it? {% for photos in x %} {% with a=photos %} <div class="row"> <div class="col-xl-12"> <div id="panel-1" class="panel"> <div class="panel-hdr"> <h2> {{ a }} <span class="fw-300"><i>Example</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <div id="js-lightgallery"> {% for photo in post %} {% if photo.ders == a %} {% if photo.img %} <a class="" href="{{photo.img.url}}" data-sub-html="{{photos.title}}"> <img class="img-responsive" src="{{ photo.img.url }}" alt="{{photo.title}}"> </a> {% endif %} {% endif %} {% endfor %} -
Django Online Market Models
Hello. I'm new to Django and want to do a project. I have some models that need to be fix. It's Online Shop and I have already done them but I'm not sure how many of them are correct. The main problem is Order and OrderRow which I think needs some changes. I explain each one of them below 1- Order.total price. I'm not sure about it. 2- Order.row I need to be able to see all objects in 'OrderRow' and the problem is when i want to save an order I need to fill 'order' object that has a foreign key to 'OrderRow' and when I want fill it I need to fill 'OrderRow.order' which is not completed. one of them I think need to be null but I'm not sure which one. 3-The rest parts, need to be done with staticmode. A: def initiate(customer) This function check if the customer has an order before or not, if he has, we must return his order and if he doesn't have, we should create a new order for him. B: def add_product here, we should add a specific product and amount to OrderRow list. I need to check if the … -
I'm getting a JSON Decode error after successfully updating a resource
I'm getting the following at after updating an index schema on the azure portal. JSONDecodeError at /updateIndex/ The schema is successfully updating, but I'm get this error along with 500 status code. This is my function @csrf_exempt def updateIndex(request): url = 'https://search-test.search.windows.net/indexes/hotels-quickstar11t?api-version=2020-06-30' index_schema = { "name": "hotels-quickstar11t", "fields": [ {"name": "HotelId", "type": "Edm.String", "key": "true", "filterable": "true"}, {"name": "HotelName", "type": "Edm.String", "searchable": "true", "filterable": "false", "sortable": "true", "facetable": "false"}, {"name": "Description", "type": "Edm.String", "searchable": "true", "filterable": "false", "sortable": "false", "facetable": "false", "analyzer": "en.lucene"}, {"name": "Description_fr", "type": "Edm.String", "searchable": "true", "filterable": "false", "sortable": "false", "facetable": "false", "analyzer": "fr.lucene"}, {"name": "Category", "type": "Edm.String", "searchable": "true", "filterable": "true", "sortable": "true", "facetable": "true"}, {"name": "Tags", "type": "Collection(Edm.String)", "searchable": "true", "filterable": "true", "sortable": "false", "facetable": "true"}, {"name": "ParkingIncluded", "type": "Edm.Boolean", "filterable": "true", "sortable": "true", "facetable": "true"}, {"name": "LastRenovationDate", "type": "Edm.DateTimeOffset", "filterable": "true", "sortable": "true", "facetable": "true"}, {"name": "Rating", "type": "Edm.Double", "filterable": "true", "sortable": "true", "facetable": "true"}, {"name": "Address", "type": "Edm.ComplexType", "fields": [ {"name": "StreetAddress", "type": "Edm.String", "filterable": "false", "sortable": "false", "facetable": "false", "searchable": "true"}, {"name": "City", "type": "Edm.String", "searchable": "true", "filterable": "true", "sortable": "true", "facetable": "true"}, {"name": "StateProvince", "type": "Edm.String", "searchable": "true", "filterable": "true", "sortable": "true", "facetable": "true"}, {"name": "PostalCode", "type": "Edm.String", "searchable": "true", "filterable": … -
Sole problems with Slug and Date Field problem in Django
I have a problem with Django code, I'm working with models to create an alternative post-creation page and the date wiget generated is a text-input. Also autocomplete not work for Slug. Someone can help me? models.py: from django.db import models from django import forms from django.contrib.auth.models import User from django.urls import reverse # Categorie class Category(models.Model): class Meta: verbose_name = 'category' verbose_name_plural = 'categories' name = models.CharField('Titolo', max_length = 250) slug = models.SlugField(max_length = 250, unique = True) desc = models.TextField('Descrizione', max_length=10000, blank=True) def __str__(self): return self.name # Articles class Article(models.Model): title = models.CharField('Titolo', max_length=100) author = models.ForeignKey(User, on_delete=models.CASCADE,) category = models.ForeignKey (Category, on_delete=models.CASCADE) desc = models.CharField('Descrizione', max_length=10000, blank=True, ) text = models.TextField('Testo', max_length=10000, blank=True) image = models.ImageField('Foto', blank=True, upload_to="img") data = models.DateTimeField('Data di pubblicazione', blank=True) slug = models.SlugField(max_length = 250, null = True, blank = True, unique=True) def get_absolute_url(self): return reverse("admin", args=(str(self.id))) class Meta: # Order post by date ordering = ['-data',] def __str__(self): return "Ciao" add_post.html: {% block content %} <h1>Add - Post</h1> <form method="POST"> {% csrf_token %} {{ form.as_p }} <button> Go</button> </form> {% endblock content %}