Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
filtering the most 4 read articles in django
I'm currently building a blog with django. I have the following blog post model. I want to select 4 most read articles because this section in the HTML file has only 4 posts. How can i do this please ? Thank you class BlogPost(models.Model): title = models.CharField(max_length=100) post_category = models.CharField(max_length=25, null=True) author = models.CharField(max_length=15) content = models.TextField(null=False, default="") post_slug = models.SlugField() date = models.DateTimeField(default=timezone.now()) number_views = models.IntegerField(default=0) #number of views post_image = models.ImageField() -
Send requests to Django through uWSGI
I have two dockers, one with nginx (Docker N) and another with django rest framework(Docker D), i have the typical set up : the web client <-> the web server <-> the socket <-> uwsgi <-> Django Now, i need to communicate with Django Rest Framework using the API endpoints, but internally , that is, inside the docker D. I don't want to use requests.get(http://my.website.com/api) because it will necessarily access the outside world and back, not very efficient. Is there a way to connect directly to the websocket from uWSGI? Should i connect to the other docker (N) through nginx instead? I tried: import websocket from websocket import create_connection ws = create_connection(ws://localhost:8000) but i always get websocket connection is already closed. , fast, too fast. I can't even send anything before the exception is thrown. Thank you. -
'function' object has no attribute 'error'
I am trying to set up simple errors for login and registration using Django. This was literally working perfectly fine up until about an hour ago when I tested it again and it is now giving me this error 'function' object has no attribute 'error'. It is not working for my registration or login so once I figure one out I can get the other one. Here is my views.py for login (just the errors portion for brevity): from django.contrib import messages from django.shortcuts import render, redirect from .models import * def login(request): errors = User.objects.logValidator(request.POST) if len(errors) > 0: for value in errors.values(): messages.error(request, value) return redirect('/') And my logValidator from the models.py: def logValidator(self, postData): user_filter = User.objects.filter(user_name=postData['user_name']) print("user Filter here: ", user_filter) errors = {} if len(postData['user_name']) == 0: errors['user_name'] = "User name is required!" elif len(postData['user_name']) < 4: errors['user_name'] = "User name must be at least 4 characters long!" elif len(user_filter) < 0: errors['user_name'] = "User name not found. Make sure you registar!" if len(postData['password']) == 0: errors['password'] = "Password is required!" elif len(postData['password']) < 4: errors['password'] = "Password must be at least 4 characters long!" elif bcrypt.checkpw(postData['password'].encode(), user_filter[0].password.encode()): print("***************") print("Password Matches!!!") else: errors['password'] = "Password … -
What is the best way to buil a python selenium website?
I want to build a website from which I can start/stop my headless selenium script and monitor the progress. Also, I want to parse user data to use in the selenium script. What is the best way to solve this problem? Django/Heroku? Jenkins? -
How to configure settings to deploy my existing Django project to PythonAnywhere?
I am having a hard time deploying my finished Django project to PythonAnywhere. It looks like it has to do with my Django secret key, which I never seem to handle correctly. The secret key is exposed in settings.py, which I know is not advised, but whenever I put it into an environment variable PythonAnywhere throws an error that it can't find it. Can anyone help me configure my settings.py + "pythonanywhere_com_wsgi.py" file to correctly deploy my application? Github link to project: https://github.com/mollycg/django-portfolio PythonAnywhere error log: Error running WSGI application 2020-12-03 22:32:51,873: decouple.UndefinedValueError: SECRET_KEY not found. Declare it as envvar or define a default value. 2020-12-03 22:32:51,873: File "/var/www/mollycg_pythonanywhere_com_wsgi.py", line 12, in <module> 2020-12-03 22:32:51,873: application = StaticFilesHandler(get_wsgi_application()) 2020-12-03 22:32:51,873: 2020-12-03 22:32:51,873: File "/home/mollycg/.virtualenvs/mgdp-venv/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2020-12-03 22:32:51,873: django.setup(set_prefix=False) 2020-12-03 22:32:51,874: 2020-12-03 22:32:51,874: File "/home/mollycg/.virtualenvs/mgdp-venv/lib/python3.8/site-packages/django/__init__.py", line 19, in setup 2020-12-03 22:32:51,874: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) 2020-12-03 22:32:51,874: 2020-12-03 22:32:51,874: File "/home/mollycg/.virtualenvs/mgdp-venv/lib/python3.8/site-packages/django/conf/__init__.py", line 76, in __getattr__ 2020-12-03 22:32:51,874: self._setup(name) 2020-12-03 22:32:51,874: 2020-12-03 22:32:51,874: File "/home/mollycg/.virtualenvs/mgdp-venv/lib/python3.8/site-packages/django/conf/__init__.py", line 63, in _setup 2020-12-03 22:32:51,874: self._wrapped = Settings(settings_module) 2020-12-03 22:32:51,874: 2020-12-03 22:32:51,874: File "/home/mollycg/.virtualenvs/mgdp-venv/lib/python3.8/site-packages/django/conf/__init__.py", line 142, in __init__ 2020-12-03 22:32:51,875: mod = importlib.import_module(self.SETTINGS_MODULE) 2020-12-03 22:32:51,875: 2020-12-03 22:32:51,875: File "./magic_django/settings.py", line 21, in <module> 2020-12-03 22:32:51,875: … -
Add entries to model with ForeignKey
I been struggling with this for a while and can't seem to find an answer on any of the other threads. I am trying to programmatically add some entries to a model in Django, the model I am trying to add to has a foreign key, and this is what I am getting hung up on. My two models are: class Post(models.Model): direct_url = models.URLField(unique=True) post_url = models.URLField() post_title = models.CharField(max_length=300) time_posted = models.DateTimeField(default=timezone.now) class Comment(models.Model): post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE) content = models.CharField(max_length=500) author = models.CharField(max_length=60) date_created = models.DateTimeField(default=timezone.now) I am trying to run some code to add some data I am pulling from another location in the DetailView (Class based view) The code that I have for that is here: class PostDetailView(DetailView): model = Post for i in hot: if i.url.endswith(Endings): post_to = model.objects.get(direct_url=i.url) submission = reddit.submission(url=f'https://www.reddit.com/r/{i.permalink}') submission.comments.replace_more(limit=None) for comment in submission.comments.list(): Comment.objects.create(post=f'{post_to}', content=f'{comment.body}', author=f'{comment.author}', date_created=f'{datetime.datetime.fromtimestamp(comment.created)}') I am trying to pull the reddit comments, and store them in a database. The problem I am running into is the following: ValueError: Cannot assign "'Post object (22)'": "Comment.post" must be a "Post" instance. What am I doing wrong? -
How to make foreign key option select autocomplete
I have a review model that is attached to a foreign key of listed companies on my site. On the review form, this list of companies comes as an option select on the html page. The user has to now scroll across many option as possible to get the particular company the wish to review. Is there a way, I can make the user input search my data in real time and they get presented with option as they type in the possible company name. Here is the nature of the review model below: class Review(models.Model): # CASCADE ensures that when a company is deleted, their reviews remains company = models.ForeignKey(Company, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) # SET_NULL ensures that when a user is deleted, their reviews get deleted too review_text = models.TextField(max_length=500, verbose_name='Your Review: (Maximum of 200 Words)') rating = Int_max.IntegerRangeField(min_value=1, max_value=5) date_added = models.DateField('Review Date', auto_now_add=True) Thanks a lot for any assitance. -
Django Multiple File Uploads
I hope someone could help me with multiple file uploads. I have found some hints online but what I am struggling with is to display title and files on one page. Please see the code bellow to understand what I am trying to achieve: models.py class Uradna(models.Model): title = models.CharField(max_length=200) date = models.DateField(default=datetime.now) file = models.FileField(blank=True, upload_to='files/') class Meta: verbose_name_plural = 'Uradna' def __str__(self): return str(self.date) class Files(models.Model): tabula = models.ForeignKey(Uradna, on_delete=models.CASCADE) title = models.CharField(max_length=200, null=True) files = models.FileField(upload_to='files/') class Meta: verbose_name_plural = 'Files' def __str__(self): return str(self.tabula.date) views.py: def homePageView(request): posts = Uradna.objects.all().order_by('-id')[:5] context = { 'posts':posts } return render(request, 'home.html', context) def filesView(request, id): post = get_object_or_404(Uradna, id=id) files = Files.objects.filter(tabula=post) return render(request, 'home.html', {'post':post, 'files':files}) urls.py urlpatterns = [ path('', homePageView, name='home'), path('<int:id>', filesView, name='home_files'), ] home.html <div class="accordion" id="accordionExample"> {% for post in posts %} <div class="card mt-3"> <div class="card-header" id="headingOne"> <h2 class="mb-0"> <button class="btn btn-link btn-block text-left" type="button" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne"> {{ post.date }} </button> </h2> </div> <div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordionExample"> <div class="card-body"> <a href="{{post.file.url}}" target="_blank">{{ post.title }}</a> </div> </div> {% endfor %} </div> </div> I have tried another for loop from the foreign key but it obviously doesn't work since urls.py … -
I am not able to Delete an item from a list in Django template
I have some lists of stations in my template when I tried deleting directly without using the confirmation modal interface it worked perfectly but when I tried using the confirmation modal, it only deleted the id of the last item in my database. How can I fix this, please? Note: Every time I click the delete button on any of the list items, every one of the show localhost:8000/deletestation/5 but I want it to delete only the specific station. views.py @login_required def DeleteStation(request, pk): station = Station.objects.get(id=pk) station.delete() context = {"station":station} return render(request, "core/stations.html", context) urls.py from django.urls import path from .views import * urlpatterns = [ path('deletestation/<str:pk>/', DeleteStation, name="deletestation"), ] stations.html <tbody> {% for station in stations %} <tr> <td>{{forloop.counter}}</td> <td>{{station.name}}</td> <td>{{station.description}}</td> <td>{{station.macaddress}}</td> <td>{{station.address}}</td> <td>{{station.ipaddress}}</td> <td>{{station.status}}</td> <td><a href="{% url 'editstation' station.pk %}"><i style="font-size: 22px;" class="fa fa-search"></i></a></td> <td data-toggle="modal" data-target="#delete_station" style="cursor: pointer;"> <i style="font-size: 22px;" class="dw dw-delete-3"></i> <div class="modal fade" id="delete_station" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Confirm Deletion</h5> <button class="close" type="button" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body">ARE YOU SURE YOU WANT TO DELETE THIS STATION</div> <div class="modal-footer"> <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button> <a class="btn btn-primary" href="{% url 'deletestation' station.pk %}">Proceed</a> … -
How do I give permission to only specific users to edit model fields in Django rest?
So I building a blog rest_api which has models class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) text = models.TextField() approved = models.BooleanField(default=False) ... class Comment(models.Model): reply_to = models.ForeignKey(Post, default=None, on_delete=models.CASCADE) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) text = models.TextField() approved = models.BooleanField(default=False) As you see both posts and comments have to be approved, posts have to be approved by admins and comments have to be approved by post owners. Also, a user who creates a post has the ability to delete, put and patch fields expect the approved field which can only be patched a superuser. Same with the comments they can be created by anyone but can only be approved by post owners and superuser. So far here are my serialisers. class CommentSerializers(ModelSerializer): class Meta: model = Comment fields = ['id','text', 'author'] read_only_fields = ['author'] class PostSerializers(ModelSerializer): comments = CommentSerializers(source='comment_set', many=True, read_only=True) class Meta: model = Post fields = [ 'id', 'text', 'author', 'approved', 'comments',] read_only_fields = ['author', 'approved',] def create(self,validated_data): user = self.context['request'].user instance=Post.objects.create(author=user ,**validated_data) return instance And here are my views and permissions Views: class PostListView(ListCreateAPIView): permission_classes = [IsAuthenticated|ReadOnly] serializer_class = PostSerializers def perform_create(self, serializer): serializer.save() def get_queryset(self): return Post.objects.filter(approved=True ).order_by('-published_date') class PostDetailView(RetrieveUpdateDestroyAPIView): permission_classes = [IsAuthenticated|ReadOnly] serializer_class = PostSerializers lookup_field … -
Gunicorn + Django + supervisor: Where are my logs?
I'm using supervisor to manage gunicorn (behind Apache) + Django. My Django LOGGING config: "version": 1, "disable_existing_loggers": False, "formatters": { "verbose": { "format": "%(levelname)s %(asctime)s %(module)s " "%(process)d %(thread)d %(message)s" } }, "handlers": { "console": { "level": "INFO", "class": "logging.StreamHandler", "formatter": "verbose", } }, "root": {"level": "INFO", "handlers": ["console"]}, "loggers": { "django.db.backends": { "level": "ERROR", "handlers": ["console"], "propagate": False, }, # Errors logged by the SDK itself "sentry_sdk": {"level": "ERROR", "handlers": ["console"], "propagate": False}, "django.security.DisallowedHost": { "level": "ERROR", "handlers": ["console"], "propagate": False, }, 'gunicorn.error': { 'level': 'INFO', 'handlers': ['console'], 'propagate': True, }, 'gunicorn.access': { 'level': 'INFO', 'handlers': ['console'], 'propagate': False, }, }, } my gunicorn config: --preload --pid /usr/home/pids/%(program_name)s -b 127.0.0.1:8124 --access-logfile /usr/home/logs/user/access_%(program_name)s.log --access-logformat "%%({x-forwarded-for}i)s %%(l)s %%(u)s %%(t)s \"%%(r)s\" %%(s)s %%(b)s \"%%(f)s\" \"%%(a)s\"" my supervisor config: stdout_logfile=/usr/home/logs/user/%(program_name)s.stdout.log stdout_logfile_maxbytes=10MB stderr_logfile=/usr/home/logs/user/%(program_name)s.stderr.log stderr_logfile_maxbytes=10MB Somehow my access log ends up in /usr/home/logs/user/%(program_name)s.stderr.log, all other logs are and stay empty (except for Apache, which also creates an access log). Since I changed "disable_existing_loggers" from True to False, now also errors end up in that log file (before they only went to sentry). Any thoughts what is going on? When I used the same LOGGING and nginx -> apache -> mod_wsgi -> django, I did receive … -
Django Channels: Updating model field when disconnecting WebSocket in messaging
I have implemented a messaging application using Django-Channels. And inside my consumer, I get the last message of every chat when a chat message is sent. Below is my consumer __init__ method and as you can see every connection has a last_message_id def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.user = None self.room = None self.messages_pre_connect_count = None self.last_message = None self.last_message_id = None Inside my consumer I have implemented a new_message() function such as: def new_message(self, data): author = data['from'] author_user = Profile.objects.get(username=author) message = Message.objects.create( author=author_user, content=data['message'], privatechat = self.room ) self.last_message = message self.last_message_id = message.id json_message = { 'id':message.id, 'author':message.author.username, 'content':message.content, 'timestamp':str(message.get_time_sent), 'last_message_content':self.last_message.content, 'last_message_time':self.last_message.get_time_sent() } content = { 'command':'new_message', 'message':json_message } return self.send_chat_message(content) Now I do not want to update the room last_message field every time I have a new message therefore inside my room model I have added a new function: def set_last_message(self, message_id): self.last_message = message_id self.save() This saves the last message-id of the field. However, if I call the model save() method inside the consumer disconnect() function it suddenly creates multiple instances of the room instead of editing the model field. def disconnect(self, close_code): self.room.set_last_message(self.last_mesage_id) async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) Now I am not using … -
How to securely connect to Azure redis from celery-django project?
I am trying to convert from a local Redis container to a managed service in Azure. I know I have the correct server name and key because redis-cli -h <server-name>.redis.cache.windows.net -p 6379 -a <azure_key> connects. Locally my connection before in celery_manager.py was app = Celery(broker=redis://redis:6379) I updated broker successfully with the non-ssl port enabled. broker=redis://:<key>@<server-name>.redis.cache.windows.net:6379 per [this question] I tried updating the broker to: broker=redis://:<key>@<server-name>.redis.cache.windows.net:6379 I got this warning in Celery log: [2020-12-03 20:54:00,491: WARNING/celery] Secure redis scheme specified (rediss) with no ssl options, defaulting to insecure SSL behaviour. And this exception in django-tasks: 020-12-03 20:54:31,223 - INFO - runworker - Using single-threaded worker. 2020-12-03 20:54:31,224 - INFO - runworker - Running worker against channel layer default (asgi_redis.core.RedisChannelLayer) 2020-12-03 20:54:31,225 - INFO - worker - Listening on channels http.request, websocket.connect, websocket.disconnect, websocket.receive Traceback (most recent call last): File "/root/miniconda3/lib/python3.6/site-packages/redis/connection.py", line 185, in _read_from_socket raise socket.error(SERVER_CLOSED_CONNECTION_ERROR) OSError: Connection closed by server. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/src/manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/root/miniconda3/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/root/miniconda3/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/root/miniconda3/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/root/miniconda3/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output … -
How to access field from ManyToMany relation on top of Foreign key relation in a django serializer?
I have the following structure: class Model_1(): model_2_ref = models.ForeignKey(to="Model_2", null=True, on_delete=models.SET_NULL) model_1_field_1 = models.CharField(max_length=120) ... class Model_2(): model_2_field_1 = models.CharField(max_length=120) model_2_field_2 = models.CharField(max_length=120) .... class Model_3(): model_2_ref = models.ManyToManyField(to="Model_2", related_name="model_2_rel_name") model_3_field_1 = models.CharField(max_length=120) .... Each record of Model_1 is related to only one record of Model_2. Also each record of the Model_2 is related to only one record of Model_3. However, a record of Model_3 can have several records in Model_2. I have a serializer for Model_1, where I would like to include it's related fields from Model_2 and Model_3. In theory, this is what I would like to achieve: class Model_1_Serializer(): model_1_field_1 = serializers.CharField() model_2_field_1 = serializers.CharField(source='model_2_ref.model_2_field_1') model_2_field_2 = serializers.CharField(source='model_2_ref.model_2_field_1') model_3_field_1 = serializers.CharField(source='model_2_ref.model_3_ref.model_3_field_1') For model_3_field_1 this syntax does not work, but for the fields of model 2 it does. How can I access the related fields of Model_3 from the serializer of Model_1? -
Django E-Commerce: cart item Iterations not pushed to db
I have the following model in my orders app: class Order(models.Model): # customer info first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='order_items', on_delete=models.CASCADE) price = models.DecimalField(max_digits=5, decimal_places=2) quantity = models.PositiveIntegerField(default=1) I have the following create_order view: def create_order(request): cart = Cart(request) if request.method == 'POST': form = CreateNewOrderForm(request.POST) if form.is_valid(): order = form.save() for item in cart: OrderItem.objects.create(order=order, product=item['product'], price=item['price'], quantity=item['quantity']) cart.clear() else: form = CreateNewOrderForm() PROBLEM On creating a new order, if my cart contained multiple products, I can only see 1 (the first) product in my OrderItem. Any advice on how to rectify this? -
dango delete function getting error (Field id expected a number but got)
i have create a delete function on django when try to delete a post using JQuery i get this error Field 'id' expected a number but got '\n \n \n i also add try to assign id over the pk but i get same error can anybody like to tell me how can i use this function using JQuery def ArticleDelete(request): if request.method == "POST": pk = request.POST.get('pk') article = get_object_or_404(Article, pk=pk) messages.success(request, 'The story was deleted successfully!') article.delete() return JsonResponse({"success": True}, status=200) else: return JsonResponse({"success": False}, status=400) urls.py urlpatterns = [ path('delete/', views.ArticleDelete, name='delete'), } index.js $('.delete').click(function () { var this_html = $(this); var pk = this_html.parent().parent().children().first().text(); $.ajax({ url: '{% url "del" %}', type: 'POST', headers: { "X-CSRFToken": '{{csrf_token}}' }, data: { pk: pk }, success: function () { this_html.parent().parent().remove(); } }); }) -
ManyToMany get a list of user with total aggregate for each of them
Last question, thanks to @Willem Van Onsem I'm almost done Is there any way to get a list of all user who belongs to main with an aggregate total of prix? class ReservationPay(generic.DetailView): model = Main def get_context_data(self, **kwargs): context = super(Reservation, self).get_context_data(**kwargs) context['user_rea'] = Reserveration.objects.filter(user= ?,all_resa_reservation=self.object).aggregate(total=models.Sum('prix'))['total'] class Rerservation(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) prix = models.DecimalField(max_digits=6,decimal_places=2) class Main(models.Model): all_resa = models.ManyToManyField('Rerservation',blank=True, related_name='all_resa_reservation') def total_price(self): return self.all_resa.aggregate(total=models.Sum('prix'))['total'] # get the total -
Problems with running call_command() in Django
I am trying to test the call_command to invoke migration. test_command.py: from django.core.management import call_command import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mytestsite.settings') call_command('makemigrations', 'testapp') After launching I get the following error: django.core.exceptions.appregistrynotready: the translation infrastructure cannot be initializated before the apps registry is ready. Check that you don`t make non-lazy gettext calls at import time error If I understand correctly, the problem is that the registered application is not visible from the file that I run. apps.py: from django.apps import AppConfig class TestappConfig(AppConfig): name = 'testapp' Structure: mytestsite: --mytestsite: ----__init__.py ----setting.py ----urls.py ----wsgi.py --testapp: ----__init__.py ----admin.py ----apps.py ----models.py ----tests.py ----urls.py ----views.py --manage.py --test_command.py --db.sqlite3 Please tell me what could be wrong. How can the error be corrected? -
How Copy And Update A Function In Django Model
I have a BlogPost Model, and I want to define a copy function in it to copy all the posts and also all its comments. Add to that; I need to update The time of the data_created as well. Finally, It needs to return the new ID post. P.s: It would be great if show me how I can be tested in Django Console. How can I copy and How can I see the result. Thank you. from django.db import models class Author(models.Model): name = models.CharField(max_length=50) def __str__(self): return '{}'.format(self.name) class BlogPost(models.Model): title = models.CharField(max_length=250) body = models.TextField() author = models.ForeignKey(to=Author, on_delete=models.CASCADE) data_created = models.DateTimeField(auto_now_add=True) ************ **Here I need your help.** def copy(self): for comment in self.comment_set.all(): comment.pk = None comment.blog_post.data_created = comment.blog_post.data_created.now() comment.save() class Comment(models.Model): blog_post = models.ForeignKey(to=BlogPost, on_delete=models.CASCADE) text = models.TextField() def __str__(self): return '{}'.format(self.text) -
How to prefetch or subquery a deeply nested object with condition in Django ORM
There are theses models and relations : Hours --FK--> Task --FK--> Project <--FK-- Period class Hour(models.Model): date = models.DateField(...) task = models.ForeignKey(Task, ...) class Task(models.Model): project = models.ForeignKey(Project, ...) class Project(models.Model): pass class Period(models.Model): project = models.ForeignKey(Project,...) start = models.DateField(...) end = models.DateField(...) Summary : Hour has one task Task has one project Period has one project Hour has a date Period has a start date and a end date For a given date and a given project there is one or none period possible I want to populate a period field in Hour objects the same way it would be done with prefetch_related (using queryset) I want to have something like this : hours = Hour.objects.prefetch_period().all() hours.first().period # Period(...) Using a custom queryset method like this : class HourQuerySet(models.query.QuerySet): def prefetch_related(self): return ??? For the moment I've only succeed doing this using annotate and Subquery, but I only manage to retrieve the period_id and not the prefetched period : def inject_period(self): period_qs = ( Period.objects.filter( project__tasks=OuterRef("task"), start__lte=OuterRef("date"), end__gte=OuterRef("date") ) .values("id")[:1] ) return self.annotate(period_id=Subquery(period_qs)) -
Is it possible for a react developer to completely override wagtail admin interface?
wagtail cms is reaaly awesome. But I like to create my own admin interface using next js (SSR react framework). I've searched for a way to interact with wagtail admin interface using a restful api. But I haven't found anything in documents. -
Django crispy forms is not working correctly
crispy forms doesn't work, I don't have any errors but the forms is still normal. Would like to have help on that. I don't understand I never had this probleme, thank you I have 'crispy_forms' in my INSTALLED_APPS and it correctly installed I tried many things but didn't get any result newhome.html {% load crispy_forms_tags %} {% load static %} {% block content %} <link rel="stylesheet" type="text/css" href="{% static 'pools/newmain.css' %}"> <!-- Load an icon library to show a hamburger menu (bars) on small screens --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <div class="topnav" id="myTopnav"> <a href="#home" class="active">Home</a> <a href="#news">News</a> <a href="#contact">Contact</a> <a href="#about">About</a> <a href="javascript:void(0);" class="icon" onclick="myFunction()"> <i class="fa fa-bars"></i> </a> </div> <div class="content-section"> <form method="POST" action=""> {% csrf_token %} {{ form|crispy }} <button class="btn btn-outline-info" type="submit">Send</button> </form> </div> {% endblock %} newmain.css body { background-color: coral; } /* Add a black background color to the top navigation */ .topnav { background-color: #333; overflow: hidden; } /* Style the links inside the navigation bar */ .topnav a { float: left; display: block; color: #f2f2f2; text-align: center; padding: 14px 16px; text-decoration: none; font-size: 17px; } /* Change the color of links on hover */ .topnav a:hover { background-color: #ddd; color: black; } /* … -
Display Arrow up or down in django
I have a column called kpi_delta_ind. If the column is 0 or 1,the arrow should be pointing upwards and downwards if it is <0. I am trying to use hexacode in my views.py file but it prints the code.Is there any way we can use hexacode in my views.py file or do i need to write condition in html file. Here is my Views.py file. def info(request): L_C_U = L_C_S = L_W_U = L_W_S =L_S_U= L_P_S= L_N_I= L_C_O=0 for row in Kpi_Data.objects.all(): if (row.kpi_Group == 'LOGIN_STATS' and row.kpi_subgroup== 'CONSUMER_PORTAL' and row.kpi_key == 'CP_USER'): L_C_U = row.kpi_value if (int(row.kpi_delta_ind) >= 0): print('&#x25B2;') elif (int(row.kpi_delta_ind) < 0): print('&#x25BC;') elif (row.kpi_Group == 'LOGIN_STATS' and row.kpi_subgroup== 'CONSUMER_PORTAL' and row.kpi_key == 'CP_SCRNS'): L_C_S = row.kpi_value elif (row.kpi_Group == 'LOGIN_STATS' and row.kpi_subgroup== 'WORKER_PORTAL' and row.kpi_key == 'WP_USER'): L_W_U = row.kpi_value elif (row.kpi_Group == 'LOGIN_STATS' and row.kpi_subgroup== 'WORKER_PORTAL' and row.kpi_key == 'WP_SCRNS'): L_W_S = row.kpi_value elif (row.kpi_Group == 'APP_STATS' and row.kpi_subgroup== 'CONSUMER_PORTAL' and row.kpi_key == 'CP_SUB'): L_S_U = row.kpi_value elif (row.kpi_Group == 'APP_STATS' and row.kpi_subgroup == 'WORKER_PORTAL' and row.kpi_key == 'WP_PAP_SUB'): L_P_S = row.kpi_value elif (row.kpi_Group == 'APP_STATS' and row.kpi_subgroup == 'REDEM' and row.kpi_key == 'RED_INIT'): L_N_I = row.kpi_value elif (row.kpi_Group == 'APP_STATS' and row.kpi_subgroup == 'REDEM' … -
Django getting NoReverseMatchexception
My root urls.py from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('', include('pages.urls')), # new ]+static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) My pages app urls.py from django.contrib import admin from django.urls import path from pages import views urlpatterns = [ path('', views.home_page, name='home_page'), path('<tab>', views.home,name='home'), ] With this, I am able to access 127.0.0.1:8000/Home 127.0.0.1:8000/About 127.0.0.1:8000/Services 127.0.0.1:8000/Portfolio All the tabs with url entry. But, when I create an url entry in html template, {% url 'About' %} getting NoReverseMatch -
Im trying to split django rows by the category Ativos like the exemple below
im getting this enter image description here but i whant this enter image description here is there a way to get this result?