Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there any way to use Pagination with django-filter?
Whenever I press on a link to the next page (which is a get request), the filter is bypassed and I get the corresponding page for the entire list (without the filter). Example, if I am on page 1 for a filtered list and I click next, I land on page 2 for the entire unfiltered list. In models.py, class Person(models.Model): name = models.CharField(max_length=50, unique=True) gender = models.CharField(max_length=7, choices=GENDER_CHOICES) category = models.CharField(max_length=20, choices=get_all_category_choices()) In filters.py, import django_filters from .models import Person class PersonFilter(django_filters.FilterSet): class Meta: model = Person fields = [ 'name', 'gender', 'category', ] In views.py, def show_all_persons_page(request): context = {} filtered_person_list = PersonFilter( request.GET, queryset=Person.objects.all() ) context['filtered_person_list'] = filtered_person_list paginated_filtered_person_list = Paginator(filtered_person_list.qs, 3) page_number = request.GET.get('page') person_page_obj = paginated_filtered_person_list.get_page(page_number) context['person_page_obj'] = person_page_obj return render(request, 'app1/show_all_persons_page.html', context) In app1/show_all_persons_page.html, <form method="get"> {{ filtered_person_list.form.as_p }} <button type="submit">Search</button> </form> {% for person in person_page_obj %} <img src="{{ person.picture.url }}" width="240"> <h2> {{person.name}} <br> {{person.gender}} <br> {{person.category}} <br> </h2> <br> {% endfor %} <div class="pagination"> <span class="step-links"> {% if person_page_obj.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ person_page_obj.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ person_page_obj.number }} of {{ person_page_obj.paginator.num_pages }}. </span> {% if person_page_obj.has_next %} <a href="?page={{ person_page_obj.next_page_number }}">next</a> <a href="?page={{ … -
date field in a Django model is not found in the returning list
I have a function to return all Django model fields as follow: The model as follow: class Posts(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Post_Category, on_delete=models.CASCADE) sub_category = models.ForeignKey(Post_Sub_Category, on_delete=models.CASCADE) title = models.CharField(max_length=64) content = models.TextField(max_length=65536) date_created = models.DateTimeField(auto_now =False, auto_now_add=True) date_updated = models.DateTimeField(auto_now=True, auto_now_add=False) def __str__(self): return "%s %s %s %s %s %s %s" % (self.id, self.category, self.sub_category, self.title, self.content, self.date_created, self.date_updated, ) class Meta: verbose_name_plural = "Post" The function inside of view function as follow: def get_forums(): ret = [] forums = Posts.objects.all().order_by('-date_updated') print(forums) for forum in forums: value = model_to_dict(forum, fields=[field.name for field in forum._meta.get_fields()]) value['user'] = {'username': forum.user.username, 'id': forum.user.id} ret.append(value) print(ret) return ret The output of first print: [<Posts: 164 cars Toyota 49 First post title This is the content of the first post 2020-04-05 14:56:25.192988+00:00 2020-04-05 14:56:25.193046+00:00>, <ForumsPosts: 163 cars Toyota this is the second post title This is the content of second post 2020-04-05 14:32:10.217224+00:00 2020-04-05 14:32:10.217351+00:00>] The output of second print: [{'id': 164, 'user': {'username': 'saleh', 'id': 1}, 'category': 4, 'sub_category': 49, 'title': 'First post title', 'content': 'This is the content of the first post '}, {'id': 163, 'user': {'username': 'saleh', 'id': 1}, 'category': 4, 'sub_category': 49, 'title': 'this … -
Make IntegerField as uniqueue in Django
I have a Model(MyClass) and this Model has some existing data. Now i want to add a auto increment column. ***Id is already there in model and this is auto increment First Approach:- i have created two migrations. in first migration i have passed default value as zero and in second migration i have passed below function as default. class MyClass(models.Model): def get_next_store_code(): ''' Returns the next value for the `code` field''' last_value = Store.objects.all().order_by('code').last() if last_value is None or last_value.code is None: return 1123 return last_value.code + 1 code = models.IntegerField(default=get_next_store_code) Now my friend told me that get_next_store_code can generate two same values.I told him like sql handle race case also but he said that first django will perform read operation and then write operation so it is possible that in read operation it can read same value for two request. Now i am trying to store default value as NULL code = models.IntegerField(default=None) so i can make it as unique but i am getting following error. django.db.utils.IntegrityError: column "code" contains null values -
How to use Django formset to update tables with foreign key
I have : 1 - two models: client models and contact model (foreign key) 2 - two forms one for the client and the other for the contact What I trying to do here, update the client table with his contact on the same view, so I have to get the contact data from the client data (foreign key), after that display both and update them using the update method. The mains difficulties that I facing is how to get the child model data from the parent model and update them I have been told that Django Formset would do the thing if anyone knows how to implement it in this context I would be grateful, thanks models.py : class Client_Data(models.Model): RC = models.CharField(max_length=50) Raison_social = models.CharField(max_length=254) NIF = models.CharField(max_length=50,unique=True) AI = models.CharField(max_length=50,unique=True) NIS = models.CharField(max_length=50,unique=True) Banque = models.CharField(max_length=50,unique=True) CB = models.CharField(max_length=50) adresse = models.CharField(max_length=50) slug = models.SlugField(blank=True, unique=True) active = models.BooleanField(default=True) class Contact(models.Model): client = models.ForeignKey(Client_Data,blank=True,on_delete=models.CASCADE) Nom = models.CharField(max_length=50) post = models.CharField(max_length=50) Tel = models.CharField(max_length=50) email = models.EmailField(max_length=255,unique=True) contact_type = models.CharField(default='Client_contact',max_length=50) views.py def client_update(request,slug): client = get_object_or_404(Client_Data, slug=slug) if request.method == 'POST': form = ClientForm(request.POST, instance=client) else: form = ClientForm(instance=client) return save_client_form_update(request, form,'Client_Section/partial_client_update_update.html') def save_client_form(request, form,Contact_form, template_name): data = … -
Django-channels Error during WebSocket handshake: Unexpected response code: 404
I was able to use django-channels but when I wanted to move with Nginx, django-channels stopped working. I am getting this error: WebSocket connection to 'ws://localhost/ws/chat/room_name/' failed: Error during WebSocket handshake: Unexpected response code: 404 What I tried: I updated Nginx config for location / Here is my Nginx.conf upstream app { ip_hash; server app:8000; } server { client_max_body_size 100M; listen 80; server_name localhost; location / { proxy_pass http://app; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; } location /static/admin { alias /app/static/admin/; } location /static/ { alias /app/static/; } } and here is my nginx in docker-compose.yml: nginx: container_name: "ngnix_master" image: nginx:latest ports: - 80:80 volumes: - ./app:/app - ./config/ngnix:/etc/nginx/conf.d - ./static:/static/ depends_on: - app -
axios.post to Django ConnectionResetError: [Errno 54] Connection reset by peer
I am going mad over a seemingly very easy task: performing a post request to a django server with a React app. post request (in React): static searchProducts(query) { console.log(queryString.stringify({'search_key':query})) const requestBody = { search_key: query } const config = { crossDomain: true, headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Access-Control-Allow-Origin': '*' } } return axios.post(API_ROUTE+'/search/', queryString.stringify(requestBody), config) .then(function (response) { console.log(response) }) .catch(function (error) { console.log(error); }); } function in Django backend: @csrf_exempt def search(request): if request.POST['search_key']: req=request.POST else: req=json.loads(request.body) if req['search_key']: if (req['search_key'][-1]) == " ": key=req['search_key'][:-1] else: key=req['search_key'] vector = SearchVector('name','brand','family','sub_family',config='italian') query = SearchQuery(key,config='italian') keys_array = key.split(" ") print(key) # rs = Product.objects.annotate(search=vector).filter(search=key) # rs = Product.objects.annotate(search=vector).filter(search__icontains__in=keys_array) q = Q() for word in keys_array: q |= Q(search__icontains = word) q |= Q(search=key) rs= Product.objects.annotate(search=vector).filter(q) rs=rs.annotate(rank=SearchRank(vector, query)).order_by('-rank').values() print(rs) return JsonResponse({'response':list(rs)}) Please note that the backend does print correctly rs, but then it trows the following error: ConnectionResetError: [Errno 54] Connection reset by peer On the FE, the error is: Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/search/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. What am I doing wrong? I am going crazy over … -
NoReverseMatch / Django / WebBlog
I am trying to attach the ID from the database to the Realting post. I don't know what's wrong. Tested it several times, but for me it looks like all the necessary things are connected. Maybe you can check and scan the logical path. I always get this error. Reverse for 'post' with keyword arguments '{'post_id': 2}' not found. 1 pattern(s) tried: ['blog/post/<int:post_id$'] Code is linked below. Ideas whats wrong? Models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse from django.utils import timezone class BlogPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) message = models.CharField(max_length=250) created_at = models.DateTimeField(default=timezone.now) def get_url(self): return reverse('blog:post', kwargs={'post_id': self.id}) views.py def post_view(request, post_id): post = get_object_or_404(BlogPost, id=post_id) return render(request, 'blog/post.html', {'post': post}) urls.py from django.urls import path from . import views app_name = 'blog' urlpatterns = [ path('', views.index, name='blog'), path('<str:username>/timeline/', views.timeline_view, name='timeline'), path('create/', views.create_post_view, name='create'), path('post/<int:post_id', views.post_view, name='post'), ] timeline.html {% extends 'blog/base.html' %} {% block blogContent %} {% if request.user.is_authenticated %} <form action="{% url 'blog:create' %}" method="post"> {% csrf_token %} {{ post_form }} <button type="submit">Senden</button> </form> {% endif %} {% for post in posts %} <p> {{ post.message }} - {{ post.created_at }} <a href="{{ post.get_url }}">#{{ post.id }}</a> </p> {% empty … -
django mezzanine customizing user
In django I expand the user model and mezzanine account profile model like this :AUTH_USER_MODEL=“App01.NewUser” ACCOUNTS_PROFILE_MODEL=“App02.MyProfile” But when I sign up a new account, the fields I add in User Model were blank.What should I do to deal with it? Thanks for answering my question! -
Where is the invalid syntax? Getting SyntaxError line 24
urlpatterns= [ url (r'^admin/', admin.site.urls) ** url (r'^about/$', views.about),** url (r'^$', views.homepage), ] ..urls.py",line 24 url (r'^about/$',views.about, SyntaxError: invalid syntax Followed tutorial and this is what the guy wrote, and keep getting error. -
Allowing Users to choose assignment View flow
I am currently working on a project with django and viewflow . I wish to allow the creator of a process to assign the task to other users , AKA allowing them to search and select from a drop down box. However there hasn't been much resources on how to go about that , would appreciate if anyone can point me in a direction , thank you! -
Bootstrap collapse doesn't collapse django
I am using django and i wanted to add a collapse function from bootstrap to my model, but it is not opening my content. I can't see whats wrong. When i click the button nothing happens. Could someone please explain me what's happening and why? Here is my code: base.html: <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Welcome to your workspace {% block title %}{% endblock %}</title> </head> <body> <div class="accordion" id="accordionQuestions"> {% block content %}{% endblock %} </div> <!----------------CLOSE CONTAINER-----------------> </body> </html> index.html: {% block content %} <h1 class="text-center mb-3">Welcome to your worspace!</h1> {% if latest_question_list %} {% for question in latest_question_list %} <div class="card mb-3"> <div class="card-header" id="heading{{ question.id }}"></div> <h2 class="mb-0"></h2> <button class="btn btn-link collapsed" type="button" data-toggle="collapse" data-target="#collapse{{ question.id }}" aria-expanded="false" aria-controls="collapse{{ question.id }}">{{ question.question_text }} </button> </h2> </div> <div id="collapse{{ question.id }}" class="collapse" aria-labelledby="heading{{ question.id }}" data-parent="#accordionQuestion" > <div class="card-body"> <h1>{{ question.question_text }}</h1> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'chiefworkspace:vote' question.id %}" class="text-center mb-3" method="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <div class="card mb-3"> <div class="card-body"> <input type="checkbox" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> <label for="choice{{ forloop.counter }}">{{ … -
how to export 3D avatar in fbx format on django-website
is there any piece of code to export my .fbx 3D avatar on the django-based website? i have gone through WebGl, three.js but can't solve the issue. thanks in advance. -
How to build a leaderboard in Django that allows for arbitrary querying and slicing?
I have a basic leaderboard in Django 2 that looks like this: from django.db import models class Leaderboard(models.Model): username = models.CharField(max_length=200) score = models.PositiveIntegerField() class Meta: indexes = [models.Index(fields=["-score"])] def __str__(self): return self.username I can produce a ranking of this leaderboard table using Django's built-in window functions Rank() and PercentRank(): from django.db.models import F, Window from django.db.models.functions import PercentRank, Rank entries = ( Leaderboard.objects.annotate( rank=Window( expression=Rank(), order_by=F("score").desc(), ), percentile=Window( expression=PercentRank(), order_by=F("score").desc(), ), ) ) print("Rank\tPercentile\tScore\tUser ID\tUser Name") for entry in entries: print(f"{entry.rank}\t{entry.percentile:.3f}\t{entry.score}\t{entry.id}\t{entry.username}") This produces a pageable table with the rankings: Rank Percentile Score User ID User Name 1 0.000 1000 564 Eager Guard 2 0.001 999 302 Top Hawk 2 0.001 999 747 Eager Whistler 2 0.001 999 842 Extreme Legend 5 0.004 997 123 Witty Guard 5 0.004 997 201 Arctic Elephant 7 0.006 996 21 Speedy Bear 7 0.006 996 678 Agile Player 9 0.008 995 562 Fast Hawk 10 0.009 994 467 Loyal Legend However, I am having difficulty querying for a specific User ID in the leaderboard and retrieving their rank and percentile. It seems that the result of the window functions are only being applied within the current queryset (ie, limited to the filter for … -
How to skip a column check with condition using Django ORM
In Django ORM how can we skip checking for a column if a condition is true? And how to check for that column with a specific value if the condition is false. For example, how can we achieve following mysql condition with Django ORM? IF(product.display_stock > 0,'0',product.hide) = 0 The need here is, if product's display_stock is > 0, then I don't care what the value of hide column contains. If display_stock = 0, then I need to confirm hide = 0. Any help form Django ORM experts is highly appreciated. Thanks. -
Webside name for Django
I just began to write some webapplications/websides on python django. I want to know -for later- is it possible to change the server name. I mean currently I have a server with a Ip port/adress and its Offline. My question is; 1) Is it possible to make the webside online on Internet for free or does it cost anythink? 2) Is it possible to get another servername/webadress than my current Ip for free or does it cost anythink? I hope I asked the questions correctly and Ill be happy if I can get a answer from Community.. Have a good day -
Django Wagtail - Images not showing up on BlogIndexPage
I am following along with the Wagtail's Your First Wagtail Site, specifically including the main image as a thumbnail alongside each post in the BlogIndexPage. Everything was working fine until I added custom HTML. Models.py: class BlogIndexPage(Page): templates = "blog/blog_index_page.html" max_count = 1 intro = RichTextField(blank=True) def get_context(self, request): # Update context to include only published guides, ordered by reverse-chron context = super().get_context(request) blogpages = self.get_children().live().order_by('-first_published_at') context['blogpages'] = blogpages return context content_panels = Page.content_panels + [ FieldPanel('intro', classname="full") ] class BlogPage(Page): templates = "blog/blog_page.html" date = models.DateField("Post date") intro = models.CharField(max_length=250, blank=True, null=True) body = RichTextField(blank=True, null=True) tags = ClusterTaggableManager(through=BlogPageTag, blank=True) categories = ParentalManyToManyField('blogs.BlogCategory', blank=True) def main_image(self): gallery_item = self.gallery_images.first() if gallery_item: return gallery_item.image else: return None search_fields = Page.search_fields + [ index.SearchField('intro'), index.SearchField('body'), ] content_panels = Page.content_panels + [ MultiFieldPanel([ FieldPanel('date'), FieldPanel('tags'), FieldPanel('categories', widget=forms.CheckboxSelectMultiple), ], heading="Blog information"), FieldPanel('intro'), FieldPanel('body'), InlinePanel('gallery_images', label="Gallery images"), ] blog_index_page.html: (Everything was working fine using Wagtail's example HTML, but once I added my own custom HTML the images stopped working. Inspect Element shows that the images .jpgs are being sourced correctly, they just don't show up. The URLS, title, and intro are working fine.) <div id="posts" class="post-grid grid-container clearfix" data-layout="fitRows"> {% for post in page.get_children … -
Pytest on Django Channels should not pass but it does
I am stuck, working with TDD my tests pass when they should not, no idea why. It should failed, Order model is not updated, so I think it should throw an error. Other thing is I could not log data when test passed. Django>=3.0.2,<3.1.0 djangorestframework>=3.11.0,<3.12.0 psycopg2>=2.8.4,<2.9.0 flake8>=3.7.9,<3.8.0 djangorestframework-simplejwt>=4.4.0,<4.5.0 channels>=2.4.0,<2.5.0 channels-redis>=2.4.2,<2.5.0 pytest-django>=3.8.0,<3.9.0 pytest-asyncio>=0.10.0,<1.0.0 test_websocket.py @database_sync_to_async async def test_user_can_create_orders(self, settings): settings.CHANNEL_LAYERS = TEST_CHANNEL_LAYERS user = await create_user( email='employee@example.com', group='user' ) client = Client() client.force_login(user=user) communicator = WebsocketCommunicator( application=channel_routing, path='/notification/', headers=[( b'cookie', f'sessionid={client.cookies["sessionid"].value}'.encode('ascii') )] ) # send JSON msg to a server. await communicator.send_json_to({ 'type': 'create.order', 'data': { 'user' : user.id, } }) response = await communicator.receive_json_from() data = response.get('data') assert data['id'] is not None assert Order.REQUESTED == data['status'] assert data['employee'] is None assert user.email == data['user'].get('email') await communicator.disconnect() models.py class Order(models.Model): REQUESTED = 'REQUESTED' ACCEPTED = 'ACCEPTED' DECLINED = 'DECLINED' STARTED = 'STARTED' IN_PROGRESS = "IN_PROGRESS" READY = "READY" COMPLETED = "COMPLETED" STATUSES = ( (REQUESTED, REQUESTED), (ACCEPTED, ACCEPTED), (DECLINED, DECLINED), (STARTED, STARTED), (IN_PROGRESS, IN_PROGRESS), (READY, READY), (COMPLETED, COMPLETED), ) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True ) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField( max_length=20, choices=STATUSES, default=REQUESTED) def __str__(self): return f'{self.id}' def get_absolute_url(self): return reverse('order:order_detail', … -
If there a more concise way of accepting user queries in a django rest framework view
I've read through the django rest framework documenation and tried to get the filter backend working with no success. My work around was to overide the get_queryset in the view: def get_queryset(self): # create a var as a dict of the query parameters passed in by the user user_query = {key: value[0] for key, value in dict(self.request.query_params).items()} # this try block prevents the format argument used to return # json from being passed as a user query try: del user_query['format'] except KeyError: pass queryset = Foo.objects.filter(**user_query) return queryset My question is; is there a more concise way of doing it? or perhaps someone who can help me understand the django filter backend better. -
creating a confirm page in django when deleting
Following a tutorial where it uses a confirm page when you click the delete button. But what he's using is a class view (not sure if that's the right term. this is how he does it class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Post success_url = '/' def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False Since I made my views different (came from a different tutorial), I want it to be consistent by using a post like usual but with a confirm page. NOTE: I do not want to use a confirm pop up like what they usually recommend on other posts. This is what I have @login_required def post_delete(request, id): post = Post.objects.get(id=id) if post.author != request.user: raise Http404("Can't find post") form = PostForm(request.POST or None, instance=post) print(form) if form.is_valid(): form.save() return HttpResponseRedirect('blog_posts_by_logged_user') context = { 'form' : form } return render(request, "blog/delete_confirm.html", context) Only issue here is, that I keep getting invalid, so I never get past the whole thing and it just reloads the confirm page. This is my delete/confirm.html template {% extends 'blog/base.html' %} {% block content %} <form method="POST" action=""> {% csrf_token %} <div>Are you sure you want to delete {{ … -
Selenium on Docker keeps giving 127 error (unexpectedly exited)
def setUp(self): chrome_options = Options() chrome_options.add_argument('--dns-prefetch-disable') chrome_options.add_argument('--no-sandbox') chrome_options.add_argument('--headless') chrome_options.add_argument('disable-gpu') self.selenium = webdriver.Chrome('./chromedriver', chrome_options=chrome_options) super(FunctionalTesting, self).setUp() Above is my functional test code for a Django website I'm building. But then I keep getting this error message. File "/builds/XXX/XXX/XXX/tests.py", line 11, in setUp self.selenium = webdriver.Chrome('./chromedriver', chrome_options=chrome_options) File "/usr/local/lib/python3.6/site-packages/selenium/webdriver/chrome/webdriver.py", line 73, in __init__ self.service.start() File "/usr/local/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 98, in start self.assert_process_still_running() File "/usr/local/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 111, in assert_process_still_running % (self.path, return_code) selenium.common.exceptions.WebDriverException: Message: Service ./chromedriver unexpectedly exited. Status code was: 127 Any idea to solve the problem? Note that the problem is not at the "./chromedriver" directory, I have set up the CI/CD script so it will have chromedriver at that spot -
How to show/hide items of the list in Django? (using JS or JQuery)
I'm writing website using Django framework, but i am newbie in this web-framework, and i don't know how to work with JavaScript in Django templates. I just wanted to show/hide items of the list onclick, but i show/hide only first or last item. My code: {% for mysong in album.song_set.all %} <li onclick=action()><a>CLICK ME</a></li> <div id="{{mysong.id}}"> <h1>{{mysong}}</h1> <img src="{{album.album_logo}}" width="300px"><br/> <h2>Song: {{mysong.song_title}}</h2> <h2>Artist: {{album.artist}}</h2> <h2> <audio controls> <source src="{{mysong.audiotrack.url}}" type="audio/mpeg"> </audio> </h2> </div> <script> function action() { var added_item_button = document.getElementById('{{mysong.id}}'); var actualDisplay = getComputedStyle(added_item_button).display; if (actualDisplay == 'none') { added_item_button.style.display = 'block'; } else { added_item_button.style.display = 'none'; } } </script> {% endfor %} That's how i tried to show/hide items of the list that i iterated over. But it seems, that's doesn't work like that. Thanks, any help will be appreciated. -
How can i show all fields in admin panel - Django
models.py class Company(models.Model): name = models.CharField(max_length=20) location = models.CharField(max_length=20) date_created = models.DateTimeField() Admin.py class CompanyAdmin(admin.ModelAdmin): list_display = [name,location,date_created] Register your models here. admin.site.register(Company,CompanyAdmin) Instead of writing write each one field(list_display = [name,location,date_created] ) there is an way to get all fields in admin??? -
Is it possible to subscribe ROS topic with a Django web-app?
I want to know if it's possible to bind ROS and Django in order to have a web-page which shows the state of a ROS controlled robot. I just want to have a Django application which subscribe a ROS topic and get the state about the robot, then this application should be able to show these data on a status page. For now I think that the easiest way is to have a ROS node which write data in files, and the Django app should open and read this data in order to show infos on a page ... But I think it's not very efficient and not bug-proof. Can you help me ? -
What is the best way for nest User serializers in Django Rest Framework?
I try to return a "Store Data" in a ModelSerializer from DRF with two keys named owner and collaborators that contain an User Serialized data. When I send a GET request I recieved only the User ID. I have this: Serializer class StoresSerializer(serializers.ModelSerializer): class Meta: model = Stores fields = "__all__" View class StoresAPI(viewsets.ModelViewSet): serializer_class = StoresSerializer queryset = Stores.objects.all() Response { "id": 13, "store_name": "Store Title", "store_website": "https://url.com.", "store_image": "https://url.com", "created_at": "2020-04-05", "owner": 2, "collaborators": [ 2, 3 ] } Deseable Response { "id": 13, "store_name": "Store Title", "store_website": "https://url.com.", "store_image": "https://url.com", "created_at": "2020-04-05", "owner": { "username": "ownerUser", "email": "user@mail.com", "id": 4, "first_name": "owner", "last_name": "LastName" }, "collaborators": [{ "username": "usr", "email": "user@mail.com", "id": 2, "first_name": "First", "last_name": "LastName" }, { "username": "usr", "email": "user@mail.com", "id": 3, "first_name": "First", "last_name": "LastName" }] } I try adding an UserSerializer in StroreSerialer but I get fields errors when I try to post data. class StoresSerializer(serializers.ModelSerializer): owner = UserSerializer() collaborators = UserSerializer(many=True) class Meta: model = Stores fields = "__all__" Thanks for read this, I hope you help me! -
how to create product auto Code generator python django
I have a product class in the Django model. Over there are product name, category and department name (foreign key). so I want to create an automatic code generator that will generate automatically like 2 or 3 alphabets as category name and 3 alphabet department name and 6 digits number. for example: COM-ELC-000001 '''class Item(models.Model): item_name = models.CharField(max_length=255, blank =True) description = models.CharField(max_length=255, blank=True, null=True) item_choice = ( ('IT','IT'), ('Electronics', 'Electronics') ) item_type = models.CharField(max_length=255, blank =True, choices = item_choice ) code = models.CharField(unique=True, max_length=255) unit = models.CharField(max_length=255, blank=True, null=True) company = models.ForeignKey(Company, on_delete = models.SET_NULL, null =True,blank=True) department = models.ForeignKey(Department, on_delete = models.SET_NULL,null= True, blank=True) '''