Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i limit the number of objects we can save by with a condition and without a condition in django?
What is meant is, I want to save only one object with is_featured field true, if user tried to save another object with is_featured field true it needs to give a prompt, How can i accomplish that in django any idea? class Event(BaseModel): title = models.CharField(max_length=200) time = models.TimeField() date = models.DateField() location = models.CharField(max_length=200) location_url = models.URLField() description = models.TextField() is_featured = models.BooleanField(default=False) image = VersatileImageField('Image', upload_to="web/events") class Meta: db_table = 'web_event' verbose_name = ('Event') verbose_name_plural = ('Event') ordering = ('auto_id',) def __str__(self): return str(self.title) -
Firebase Cloud Messaging registration token - Flutter and Django
I am trying to send push notifications (iOS, Android, Web) to specific users when certain events happen in my app. I am using the firebase_admin python plugin with Django, working properly for authentication and verifying jwt, but it is giving me this error when trying to send a Message/Notification from Django: firebase_admin.exceptions.InvalidArgumentError: The registration token is not a valid FCM registration token I am getting the token directly from my Flutter instance and sending it in the request body from Flutter to Django. My method for getting the token from Flutter: await FirebaseMessaging.instance.getToken().then((token) async { fcm_token = token!; }).catchError((e) { print(e); }); My python code that sends notification: registration_token = self.context['request'].data["token"], # See documentation on defining a message payload. message = Message( notification=Notification( title='New Product Added', body='A new product called ' + validated_data['name'] + ' has been added to your account.', ), token=str(registration_token) ) # Send a message to the device corresponding to the provided # registration token. response = send(message) I have verified that the token being passed to Django is correct, by comparing it to what I am getting from Flutter -
Building chart using charjs in Django
I need to create a chart with chartjs with displaying month wise count on current year in a line chart. The data should be retrieved from the model named "invoice" and the feild name is "Invoice_date". Note: Invoice_date is an DateFeild(). in views.py def home(request): if request.user.is_authenticated: customers = User.objects.filter(groups__name='Customer').count() totalinvoice = invoice.objects.all().count() supplier = User.objects.filter(is_staff=True).count() # chart labels = ["Jan","Feb","Mar","Apr","Jun","Jul","Aug","Sep","Oct","Nov","Dec"] data = [12,14,19,25,28,80,23,35,46,78,45,23] // This data's should be retrieved dynamically return render(request, 'home.html', { 'totalinvoices':totalinvoice, 'customers':customers, 'supplier':supplier, "labels":json.dumps(labels), "data":json.dumps(data), }) else: return redirect("login") Please someone help me in figuring out. -
Django: How can I show the name instead of the id in the list?
I have a form to create a user, when displaying the data in the list the foreign keys are shown with the id, how can I make the name appear instead of the id? I'm trying to do it with a for inside the template but it doesn't show me anything my user table has the cargo_empleado table as a foreign key and inside the cargo_empleado table I have a column called nombre_cargo, the column nombre_cargo I want to be displayed instead of the id template <td class="ps-0 pe-0"> {% for cargo_empleado in request.user.cargo_empleado %} {% if cargo_empleado.nombre_cargo == 'funcionario' %} <a href="" class="btn btn-info btn-sm no-hover" style="cursor: default; border-radius: 2rem; pointer-events: none;">Funcionario</a> {% endif %} {% if cargo_empleado.nombre_cargo == 'diseñador' %} <a href="" class="btn btn-warning btn-sm no-hover" style="cursor: default; border-radius: 2rem; pointer-events: none;">Diseñador</a> {% endif %} {% endfor %} <!-- {% if display.7 == 1 %} <a href="" class="btn btn-info btn-sm no-hover" style="cursor: default; border-radius: 2rem; pointer-events: none;">Funcionario</a> {% else %} <a href="" class="btn btn-warning btn-sm no-hover" style="cursor: default; border-radius: 2rem; pointer-events: none;">Diseñador</a> {% endif %} --> </td> -
Web Application Technologies and Django, (string that looks like 53656C696E613333) 2022
my wish is to know exactly what are asking for in this part of the final exercise of week 5 of the course (Web Application Technologies and Django University of Michigan). enter image description here enter image description here I understand that I have to run the above in pythonanywhere and... 1) I don't know if I have to enter the same code written there in the text box above, 2) I have to enter the outputs of said code in the text box, 3) I have to enter in the text box the code corresponding to the question shaded in blue in the image or its output or the code of the question with the output??? Besides, if possible, I would like to know what exactly asks that question. I don't know if I should update the first value of the table so that its hexadecimal (name, age) returns that "53656C696E613333" or something else. I appreciate the help. -
Each child in a list should have a unique "key" prop error with uuid as key react
I'm getting an "Each child in a list should have a unique "key" prop." in console here specifically (it quotes the first line as the relevant line) <Dropdown.Menu variant="dark"> {[ [0, "prod_name", "Name"], [1, "price", "Price"], [2, "average_rating", "Rating"], ].map((item, i) => ( <> <Dropdown.Item as={Button} key={uuid.v4()} onClick={() => { this.setState({ sort: item[0], open: false }); this.context.sort(item[1], "asc"); }} className={ this.state.sort === item[0] ? "text-black giBold active" : "text-light" } > {item[2] + " (ascending)"} </Dropdown.Item> <Dropdown.Item as={Button} key={uuid.v4()} onClick={() => { this.setState({ sort: item[0] + 3, open: false }); this.context.sort(item[1], "desc"); }} className={ this.state.sort === item[0] + 3 ? "text-black giBold active" : "text-light" } > {item[2] + " (descending)"} </Dropdown.Item> </> ))} </Dropdown.Menu>; I changed the key to be uuid since I realised tonnes of id's of different items are going to be the same in hopes that it would fix the error yet it keeps popping up. Is there something else at play here that I've missed, I tried looking for answers but couldn't find much. -
Save multiple files in a database with multiple submit buttons on a single html page
I am building a website in python django and I am new to this. Is there a way I can save multiple files with multiple submit buttons on the same html page. I created a table to store them separately. Any assistance would be appreciated. -
websockets with Django channels rest framework in docker-compose
I've made an application with two websockets connections using Django channels rest framework. Locally, everything works fine. I have such settings: #routing.py from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application from django.urls import re_path from gnss.consumers import CoordinateConsumer # noqa from operations.consumers import OperationConsumer # noqa websocket_urlpatterns = [ re_path(r'ws/coordinates/', CoordinateConsumer.as_asgi()), re_path(r'ws/operations/', OperationConsumer.as_asgi()), ] application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': AuthMiddlewareStack( URLRouter(websocket_urlpatterns) ), }) # consumers.py from djangochannelsrestframework.decorators import action # noqa from djangochannelsrestframework.generics import GenericAsyncAPIConsumer # noqa from djangochannelsrestframework.observer import model_observer # noqa from djangochannelsrestframework.observer.generics import action # noqa from djangochannelsrestframework.permissions import AllowAny # noqa from .models import Coordinate from .serializers import CoordinateSerializer class CoordinateConsumer(GenericAsyncAPIConsumer): queryset = Coordinate.objects.all() serializer_class = CoordinateSerializer permission_classes = (AllowAny,) @model_observer(Coordinate) async def coordinates_activity(self, message, action=None, **kwargs): await self.send_json(message) @coordinates_activity.serializer def coordinates_activity(self, instance: Coordinate, action, **kwargs): return dict(CoordinateSerializer(instance).data, action=action.value, pk=instance.pk) @action() async def subscribe_to_coordinates_activity(self, request_id, **kwargs): await self.coordinates_activity.subscribe(request_id=request_id) As for the consumers.py for the ws/operations/ it's exactly the same. When I run my Django app on local machine in development server (python manage.py runserver) everything works fine. But for some reason, when I run my app in docker-compose, ws/operations/ works, but ws/coordinates not. I don't recieve messages from Django for … -
django: How to write JavaScript fetch for url with slug parameter?
A django and async newbie here, trying to improve a simple message-board app. I'm sure you've all seen this problem dozens of times, but I'm unable to find a solution... Currently, when a user likes a posted message, it refreshes the whole page. I'd like to use simple JavaScript with the fetch API to prevent this, without having to resort to Ajax, as I've never used it. The problem is, I'm very new to the fetch method as well and I'm struggling to find the correct syntax for the url in the fetch request, as it uses the post model's slug field as a parameter. Like so: urls.py urlpatterns = [ ... path('post/<slug:slug>/', views.FullPost.as_view(), name='boards_post'), path('like/<slug:slug>/', views.PostLike.as_view(), name='post_like'), ... ] models.py ... class Post(models.Model): """ Model for message posts """ STATUS = ((0, "Draft"), (1, "Published")) title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey( User, on_delete=models.CASCADE, related_name="board_posts" ) category = models.ForeignKey( Category, on_delete=models.CASCADE, default="", related_name="category_posts" ) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) content = models.TextField() post_image = CloudinaryField('image', default='placeholder') status = models.IntegerField(choices=STATUS, default=0) likes = models.ManyToManyField(User, related_name="post_likes") class Meta: # Orders posts in descending order ordering = ['-created_on'] def __str__(self): return self.title def number_of_likes(self): return self.likes.count() def … -
URL to redirect related model instance django
I have a 2 models with ForeignKey linked to each other class Moc(models.Model): title = models.CharField(max_length=128, blank=False) scope = models.TextField(max_length=128, blank=False) .... def __str__(self): return self.title class Verifier(models.Model): moc = models.ForeignKey(Model1, related_name='verifiers' on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) approve = models.BooleanField(default=False). reject = reject = models.BooleanField(default=False) .... def __str__(self): return str(self.id) I have a respective forms, views and templates to create, update, delete records. def verifier_signoff_view(request, pk): verifier = Verifier.objects.get(pk=pk) form = VerifierSignForm if request.method == 'POST': form = VerifierSignForm(request.POST, instance=verifier) if form.is_valid(): form.save(commit=False) if verifier.approve is True and verifier.reject is True: return HttpResponseForbidden('You have either APPROVE or REJECT - operation not allowed!') else: form.save() return redirect('verify_coorinate' pk=verifier.moc_id) # This is where I need help... else: return render(request, 'moc/verify_signoff.html', context={'verifier': verifier, 'form': form}) What I want is that after I update Model2 instance as per above view, I want to redirect back to Model1 instance rather than verifier instance. Any help please... -
Django - formset working with multiple forms
I have three different models illustrated as below and I want to be able to edit three different forms in formset. models.py class Parent(models.Model): parent_name = models.CharField(max_length=20) class Child(models.Model): child_name = models.CharField(max_length=20) parent = models.ForeignKey("Parent",on_delete=models.PROTECT) birth_place = models.OneToOneField("BirthPlace", on_delete=models.PROTECT) class BirthPlace(models.Model): place_name = models.CharField(max_length=20) forms.py ChildrenFormset = inlineformset_factory(Parent, Child, fields='__all__', extra=0) So far, I have managed to create a formset where I can work with Parent and Child. Also, in html, I have written some javascript to add a child form dynamically. Now the problem is embedding form for BirtPlace. I have tried the below: def add_fields(self, form, index): super(ChildrenFormset, self).add_fields(form, index) form.initial['birth_place_name']=form.instance.birthplace.place_name However, it throws RelatedObjectDoesNotExist. Can you please help? Thanks -
pip не устанавливает channels_redis
Я не могу установить channels_redis с помощью pip. Using legacy 'setup.py install' for hiredis, since package 'wheel' is not installed. Installing collected packages: hiredis, async-timeout, aioredis, channels_redis Running setup.py install for hiredis ... error error: subprocess-exited-with-error × Running setup.py install for hiredis did not run successfully. │ exit code: 1 ╰─> [17 lines of output] C:\Users\Илья\AppData\Local\Temp\pip-install-dmtn5wae\hiredis_fe10fb4a81324558bcaf79034747e0f0\setup.py:7: DeprecationWarning: the imp module is deprecated in favour of importlib and slated for removal in Python 3.12; see the module's documentation for alternative uses import sys, imp, os, glob, io C:\Users\Илья\AppData\Local\Programs\Python\Python310\lib\site-packages\setuptools\dist.py:717: UserWarning: Usage of dash-separated 'description-file' will not be supported in future versions. Please use the underscore name 'description_file' instead warnings.warn( running install running build running build_py creating build creating build\lib.win-amd64-3.10 creating build\lib.win-amd64-3.10\hiredis copying hiredis\version.py -> build\lib.win-amd64-3.10\hiredis copying hiredis_init_.py -> build\lib.win-amd64-3.10\hiredis copying hiredis\hiredis.pyi -> build\lib.win-amd64-3.10\hiredis copying hiredis\py.typed -> build\lib.win-amd64-3.10\hiredis running build_ext building 'hiredis.hiredis' extension error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: legacy-install-failure × Encountered error while trying to install package. ╰─> hiredis note: This is an issue with the package mentioned above, not pip. hint: … -
No module named 'requests' - Django deployment onto Heroku
Deployed some new code into an app on Heroku and now showing the following message: No module named 'requests' . The app was working fine before, so this has to be something I changed. Before I show the code there is 2 things that I noticed: my Procfile & requirements files are not visible from Visual Studio (can be seen from Sublime Text Editor). Recently started using VS and only noticed it now. Not sure if this is of importance here. I am not sure where the error is coming from so I left below traceback, Procfile and requirements.txt files. Let me know if I need to add something else. Traceback $ git push heroku master Enumerating objects: 111, done. Counting objects: 100% (111/111), done. Delta compression using up to 4 threads Compressing objects: 100% (80/80), done. Writing objects: 100% (81/81), 129.38 KiB | 2.59 MiB/s, done. Total 81 (delta 23), reused 1 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Using buildpack: heroku/python remote: -----> Python app detected remote: -----> No Python version was specified. Using the same version as the last build: python-3.10.5 remote: … -
NGINX giving me `ERR_TOO_MANY_REDIRECTS` in the browser, but no error is showing in the terminal
I have a set up a nginx on subdomain backend.globeofarticles.com, and the frontend is served on cloudfare on domain www.globeofarticles.com and globeofarticles.com, also my code for the backend is deployed on a vps, the frontend is deployed on cloudfare, the main problem is that nginx is giving me ERR_TOO_MANY_REDIRECTS on the browser, screenshot: here is some code that might help tracking the problem: on /etc/nginx/nginx.conf file : user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; # gzip_vary on; # gzip_proxied any; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; # gzip_vary on; # gzip_proxied any; # gzip_comp_level 6; # gzip_buffers 16 8k; # gzip_http_version 1.1; # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/x$ ## # Virtual Host Configs ## # # EDIT HERE include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; … -
Sharing user profiles in two Django projects
I was wondering if it possible to create two Django website Both work independently. If the User signup on site A The new contact information will be sent to site B using API automatically. If the user adds a post on site A, site B gets its copy. Site B is the parent of multiple sites like site A owned by users. The users create something on their local site, and B gets a copy of the user push. I'm looking to create a federated network of multiple social websites and a Base website for the storing of Public posts only. -
Django editing view/template for Froala form
I wanna use Froala editor form for creating and editing articles in my site. I can create any article with this form/can get data from editor, but i don't know how to insert article data from DB through view function into {{ form }} in my template. How to do this? -
"local variable 'form_b' referenced before assignment django"
def register(request): if not request.user.is_authenticated: if request.POST.get('submit') == 'sign_up': form = RegisterForm(request.POST) if form.is_valid(): form.save() form = RegisterForm() elif request.POST.get('submit') == 'log_in': form1 = LogInForm(request=request, data=request.POST) if form1.is_valid(): uname = form1.cleaned_data['username'] upass = form1.cleaned_data['password'] user = authenticate(username=uname, password=upass) if user is not None: login(request, user) return redirect('/') else: form_b = LogInForm() form = RegisterForm() return render(request, 'auth.html', {'form': form, 'form1': form_b}) This above is my view function <form class="loginForm" action="" method="POST" novalidate> {% csrf_token %} {% for field in form %} <p> {{field.label_tag}} {{field}} </p> {% endfor %} <button type="submit" class="btnLogin" name='submit' value='sign_up'>Sing Up</button> </form> <form class="loginForm" action="" method="post" novalidate> {% csrf_token %} {% for field in form1 %} <p> {{field.label_tag}} {{field}} </p> {% endfor %} <button class="btnLogin" type="submit" name='submit' value='log_in'>Log In </button> </form> rendering two forms in a view function code is working fine but when i click on signup this error occur which says "local variable 'form_b' referenced before assignment django" -
/o/token is not working in django oauth2_provider
I have setup django setup locally with oauth2_provider toolkit, right now https://{domain}/o/applications/ url is working fine, but when I went through documentation I found out oauth2_provider has few more inbuilt URL's like base_urlpatterns = [ re_path(r"^authorize/$", views.AuthorizationView.as_view(), name="authorize"), re_path(r"^token/$", views.TokenView.as_view(), name="token"), re_path(r"^revoke_token/$", views.RevokeTokenView.as_view(), name="revoke-token"), re_path(r"^introspect/$", views.IntrospectTokenView.as_view(), name="introspect"), ] management_urlpatterns = [ # Application management views re_path(r"^applications/$", views.ApplicationList.as_view(), name="list"), re_path(r"^applications/register/$", views.ApplicationRegistration.as_view(), name="register"), re_path(r"^applications/(?P<pk>[\w-]+)/$", views.ApplicationDetail.as_view(), name="detail"), re_path(r"^applications/(?P<pk>[\w-]+)/delete/$", views.ApplicationDelete.as_view(), name="delete"), re_path(r"^applications/(?P<pk>[\w-]+)/update/$", views.ApplicationUpdate.as_view(), name="update"), # Token management views re_path(r"^authorized_tokens/$", views.AuthorizedTokensListView.as_view(), name="authorized-token-list"), re_path( r"^authorized_tokens/(?P<pk>[\w-]+)/delete/$", views.AuthorizedTokenDeleteView.as_view(), name="authorized-token-delete", ), ] But in my case I am not able to access https://{domain}/o/token/ -
Django migrations RunPython reverse function
In the documentation there is a mention of a reverse function in RunPython in django migrations https://docs.djangoproject.com/en/4.0/ref/migration-operations/#runpython When does the reverse function run? Is there a specific command to run the reverse function? -
Cant't remove blue link text decoration from button
I have have link button but I cant remove the blue link decoration inside my update button(class=updatebut) I have tried many thins such as putting !important on my css file and it not working either I also tried .box-table2 .updatebut a {} but it doesnt work either EDIT : I AM USING THE DJANGO FRAMEWORK. CAN THAT CAN CAUSE THE PROBLEM? here is my html file. dashboard.html body { background-color: rgb(29, 26, 39); background-image: linear-gradient(135deg, rgba(255, 102, 161, 0.15) 0%, rgba(29, 26, 39, 0.15) 35%); color: white; } .box-table2 { width: 900px; top: 0; bottom: 0; left: 0; right: 0; margin: auto; margin-top: 120px; } .table { color: white; } .thead-color { background-color: rgb(81, 45, 168); } .updatebut { padding: 4px 20px; border-radius: 4px; color: white; background-image: linear-gradient(to right, rgb(103, 58, 183), rgb(81, 45, 168)); border: none; font-size: 15px; margin-right: 20px; } .updatebut a { text-decoration: none !important; } <div class="box-table2"> <table class="table"> <thead class="thead-color"> <tr> <th scope="col">Account</th> <th scope="col">Server</th> <th scope="col">Telegram</th> <th scope="col">Balance</th> <th scope="col">Risk %</th> <th scope="col">Actions</th> </tr> </thead> <tbody> {% for accounts in data %} <tr> <td>{{accounts.accountid}}</td> <td>{{accounts.mt5server}}</td> <td>{{accounts.telegramchannel}}</td> <td>{{accounts.balance}}</td> <td>{{accounts.riskpertrade}}</td> <td><a href="{% url 'update-account' accounts.id %}" class="updatebut">Update</a><a href="{% url 'delete-account' accounts.id %}" class="deletebut">Delete</a></td> </tr> {% endfor … -
DJANGO STORED PROCEDURES ERROR-> cursor object has not attribute’callproc’”
I’m using mssql driver to make a connection with an sql server database in django, the thing is that in my views.py I’ve already import ‘from django.db import connection’ to open a cursor, then I use the next script to register a new user (django—>sql server): cursor = connection.cursor() cursor.callproc(‘[dbo.SP_UC_CREATE]’,[name, lastname,password,email]) This written inside a views.py called: “def createUser(name,lastname,password,email): The error message in the explorer is ‘pyodbc.Cursor’ object has no attribute ‘callproc’ *in my function request I’m just calling the function ‘createUser()’ giving it the parameters -
How can i used column named class in django?
I need use column named class. But class is a keyword reserved in python. models.py class Colecao(models.Model): class = models.CharField(max_length=50,blank=True,verbose_name="Classe") -
Django. not able to access staticfiles in local development
I am trying serve static files in my local development (on same server I serve my site). I have run ./manage.py collectstatic with the following configs: settings.py STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles/') template.html <img src="{% static 'apis/icons/random-svgrepo-com.svg' %}" style="width: 50px;"> Now I have staticfiles folder in my BASE_DIR folder, but when I try to get an image, it doesn't appear to be working expected. http://127.0.0.1:8000/static/apis/icons/random-svgrepo-com.svg Please help. What I am doing wrong? -
Select two entries from foreign-key/one-to-one field
So I have a Team class: class Team(models.Model): name = models.CharField(max_length=255) players = models.IntegerField() and I want to select team1 and team2 separately in Match class : class Match(models.Model): team1 = models.OneToOneField(Team,related_name=team1 ,on_delete=models.CASCADE) team2 = models.OneToOneField(Team,related_name=team2, on_delete=models.CASCADE) but I get error (Add or change a related_name argument to the definition for 'tournament.Match.team1' or 'tournament.Match.team2'.) what am I missing ? -
How to avoid copy-past with getting the same object, but with different params in Django view
My view: def get(self, request, category_id): category = get_object_or_404(Category, id=category_id) uncompleted_tasks = Task.objects.filter(category_id=category_id, execution_status=False) completed_tasks = Task.objects.filter(category_id=category_id, execution_status=True) context = { "does_not_exist_msg": "There are no todos", "category": category, "uncompleted_tasks": uncompleted_tasks, "completed_tasks": completed_tasks, } return render(request, self.template_name, context) So, I wanna get objects and handle exceptions, but not like this: try: uncompleted_tasks = Task.objects.filter(category_id=category_id, execution_status=False) except (KeyError, Task.DoesNotExist): uncompleted_tasks = None try: completed_tasks = Task.objects.filter(category_id=category_id, execution_status=True) except (KeyError, Task.DoesNotExist): completed_tasks = None How to avoid copy-paste which I demonstrated upper?