Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Any way we can share a specific item publicly from a private S3 bucket?
The question is pretty vague but here's the entire problem statement. I am using Django REST APIs, and I'm generating invocies for my clients. Using wkhtmltopdf, I'm able to generate a PDF file which gets automatically backed up to S3. Now, we need to retreive the said invoice once our client clicks on a link. We're using pre-signed URLs right now, which last for 12 hours, right? Once that link expires, the entire backend fails. I mean, even if we go for permanent pre-signed links, would there not be a security issue? I could really use some guidance on this. -
Notification template only printing out items after the 3rd position
Notification template only printing out items after the 3rd position. When I inspect element to check if its showing up in the frontend, its there, but its just a blank html <p> tag. Other than this minor bug it works fine. Not sure how to proceed, any help is much appreciated. Here are my models.py class Notification(models.Model): MESSAGE = 'message' APPLICATION = 'application' CHOICES = ( (MESSAGE, 'Message'), (APPLICATION, 'Application') ) to_user = models.ForeignKey(User, related_name='notifications', on_delete=models.CASCADE) notification_type = models.CharField(max_length=20, choices=CHOICES) is_read = models.BooleanField(default=False) extra_id = models.IntegerField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(User, related_name='creatednotifications', on_delete=models.CASCADE) class Meta: ordering = ['-created_at'] notification views.py @login_required def notifications(request): goto = request.GET.get('goto', '') notification_id = request.GET.get('notification', 0) extra_id = request.GET.get('extra_id', 0) if goto != '': notification = Notification.objects.get(pk=notification_id) notification.is_read = True notification.save() if notification.notification_type == Notification.MESSAGE: return redirect('room', pk=notification.extra_id) elif notification.notification_type == Notification.APPLICATION: return redirect('room', pk=notification.extra_id) return render(request, 'notification/notifications.html') notifications.html template {% extends 'main.html' %} {% block content %} <div class="container"> <h1 class="title">Notifications</h1> {% if not notifications %} No notifications yet! {% endif %} {% for notification in notifications %} <div class="notification"> <p> {% if notification.notification_type == 'message' %} <a href="{% url 'notifications' %}?goto=room&notification={{ notification.id }}&extra_id={{ notification.extra_id }}"> <strong>{{ notification.created_by.username }}</strong> sent you a … -
Django: Strange error with connection between view, template and url
I have two main usage and main model pages, in which products from a specific usage or model are listed. I have the following views for these pages: def get_common_queryset(): usage_queryset = Usage.objects.all() sub_usage_queryset = SubUsage.objects.all() main_model_queryset = MainModel.objects.all() pump_type_queryset = PumpType.objects.all() queryset_dictionary = { "usage_queryset": usage_queryset, "sub_usage_queryset": sub_usage_queryset, "main_model_queryset": main_model_queryset, "pump_type_queryset": pump_type_queryset, } return queryset_dictionary def products_usage_main(request): queryset_dictionary = get_common_queryset() context = queryset_dictionary return render(request, "products/products_usage_main.html", context) def products_model_main(request): queryset_dictionary = get_common_queryset() context = queryset_dictionary return render(request, "products/products_model_main.html", context) Here we have a get_common_queryset() view, which you can read about the reason of it in this question. Then we have two simillar view functions, products_usage_main and product_model_main but with different templates. In the urls.py I have following paths for these views: urlpatterns = [ path("application/", products_usage_main, name="products_usage_main"), path("model/", products_model_main, name="products_model_main"), ] In which, again, we can see that the two paths are similar with just different views. And finally I have two separate templates for these two views, which their code is not needed or related to the problem I'm facing. THE PROBLEM: In my products page sidebar, I have two main links referencing /products/application/ and /products/model/, and when I click on the /products/application/, everything works just fine; but … -
Django database design
I want to design a data model in Django with the following fields. Student's First name Student Lastname Fee per hour Dates and times of attendance. student photo. Boolean field as to student present or absent. I want to have a monthly summary of each student who attended and the total fee for that Month. Similar to a printout I can send to parents as to how much they have to pay. So my website App has to calculate for the end of each month. How do I design it? Thanks for the help -
DJANGO ORM LEFT JOIN [closed]
SQL: ` select u1.summaryUpdatedOn, u2.summary from sdgdb.user as u1 left join sdgdb.user as u2 on u1.user_id = u2.user_id and (u2.summaryUpdatedOn != '20221207030805'or u2.summaryUpdatedOn is null) where u1.sdgid = 'SDG-s6547df1445-ece35e6e-c1ea-45ae-83e8-9d9c19fab0cd'; ` my Models: ` class User(BaseModel): customer = models.ForeignKey( Customer, null=False, on_delete=models.PROTECT, db_column="customerid" ) group = models.ForeignKey( Group, null=False, on_delete=models.PROTECT, db_column="groupid" ) licensetype = models.ForeignKey( LicenseType, null=False, on_delete=models.PROTECT, db_column="licensetypeid" ) sdgid = models.CharField( max_length=64, null=False, default="temp-" + str(uuid.uuid4()), editable=False, db_column="sdgid", ) name = models.CharField(max_length=100, null=False, default=None, db_column="name") email = models.EmailField( max_length=254, unique=False, blank=True, null=True, db_column="email", ) note = models.CharField( max_length=500, null=True, blank=True, default=None, db_column="note" ) licensekey = models.CharField(max_length=100, null=True, db_column="licensekey") isdisabled = models.BooleanField(null=False, default=False, db_column="isdisabled") summary = models.TextField(null=True, db_column="summary") summaryupdatedon = models.CharField( max_length=14, null=True, db_column="summaryupdatedon" ) ` I didn't switch from SQL to API query. Please help me -
Is there a way to encrypt the password when creating a normal user through django admin?
is there any way to save password in encrypted form while creating a new user through django admin? from django.db import models from django.contrib.auth.models import AbstractUser from src.core.models import TimeStamp class User(AbstractUser, TimeStamp): joined_date = models.DateField('date joined', null=True) leave_date = models.DateField('Leave Date', null=True) role = models.ForeignKey("Role", on_delete=models.SET_NULL, null=True) class Meta: verbose_name = 'user' verbose_name_plural = 'users' def __str__(self): """ username of each user """ return self.username Here is my user model given above -
I want red borders on form submit on invalid fields using django template language
This is my html file I want red borders on form submit on invalid fields using django template language I want red borders on form submit on invalid fields using django template language I want red borders on form submit on invalid fields using django template language {% block body %} {% include 'navbar.html'%} <!DOCTYPE html> <html> <head> <title></title> <body> <form autocomplete="off" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="mb-3"> <label for="Title" class="form-label">Title</label> {{form.title}} <div class="form-text">{{form.title.errors}}</div> </div> <div class="mb-3"> <label for="Written By" class="form-label">Written by</label> {{form.written_by}} <div class="form-text"> {{ form.written_by.errors }} </div> </div> <div class="mb-3"> <label for="Description" class="form-label">Description</label> {{form.description}} <div class="form-text">{{form.description.errors}}</div> </div> <div class="mb-3"> <label for="image" class="form-label">Image</label> {{form.image}} <div class="form-text">{{form.image.errors}}</div> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> <style> .form-control { width: 50%; } .errorlist { list-style-type: none; color: red; position: relative; right: 31px; } form { margin-left: 30%; margin-right: 30%; } textarea { height: 4em; width: 50em; } </style> </body> </head> </html> {% endblock %} I want red borders on form submit on invalid fields using django template language I want red borders on form submit on invalid fields using django template language I want red borders on form submit on invalid fields using django template language -
Django an JavaScript: document.getElementById return always Uncaught TypeError: Cannot set properties of null (setting 'innerHtml')
I am writing to you because I am stuck on a basic operation (almost ashamed). I'm working on a Django project and what I'm trying to do is: show inside two 'span' tags the length of a list. It's not the first time I've done this and I've always managed to do it. But now I don't understand why it doesn't work. Here is the code: My index.html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Free Attitude</title> <!-- BOOTSTRAP CSS --> <link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}"> <!-- CSS --> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <!-- JS --> <script type="text/javascript" src="{% static 'js/templatesList.js' %}"></script> </head> <body> {% include '_header.html' %} <main class='home-main'> <div class="container"> <section class="row gy-3"> <!-- FOR LG SCREEN --> <div class="col-md-6 text-container d-md-block d-none"> <h2>Modelli per siti web</h2> <h6>Dai un'occhiata ad alcuni modelli già pronti, protresti trovare qualcosa di tuo interesse.</h6> <a href="{% url 'websiteEcomm:home' %}">Vedi tutti e <span id="total-templates-lg"></span> i modelli disponibili</a> </div> <div class="col-md-6 d-md-block d-none"> <div id="carouselExampleSlidesOnly" class="carousel slide" data-bs-ride="carousel" data-bs-interval="2000"> <div class="carousel-inner"> <div class="carousel-item active"> <img src="{% static 'preview-img/arsha.png' %}" class="d-block w-100" alt="..."> </div> <div class="carousel-item"> <img src="{% static 'preview-img/digimedia.png' %}" … -
How to Reset form field after submit in HTMX
I'm tried to reset form field after submit the data in HTMX. Please guide me how to do. -
Access fields dynamically in a django serilaizer
I am trying to acsess fields of a model dynamically(on the basis of call from frontend) in the serializer but unable to do so code: class DynamicFieldsModelSerializer(serializers.ModelSerializer): def __init__(self, *args, **kwargs): super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs) print("self", self) fields = self.context['request'].query_params.get('fields') if fields: fields = fields.split(',') # Drop any fields that are not specified in the `fields` argument. allowed = set(fields) existing = set(self.fields.keys()) for field_name in existing - allowed: self.fields.pop(field_name) class ProductTestSerializer(DynamicFieldsModelSerializer, serializers.ModelSerializer): class Meta: model = Product fields = ("id",) class ProductTestAPIView(generics.ListAPIView): def get(self, request): obj = Product.objects.all() data = ProductTestSerializer(obj, many=True) s_data = data.data return Response(s_data) URL: http://127.0.0.1:8000/products-test/?fields=id,short_code It returns the following error: KeyError: 'request' at fields = self.context['request'].query_params.get('fields') -
Regarding python django
error while migrating webapp.Login.user_permissions: (fields.E304) Reverse accessor for 'webapp.Login.user_permissions' clashes with reverse accessor for 'auth.User.user_permissions' models from django.contrib.auth.models import AbstractUser from django.db import models from django.conf import settings # Create your models here. class Login(AbstractUser): is_student=models.BooleanField(default=False) class Student(models.Model): user= models.OneToOneField(Login,on_delete=models.CASCADE,related_name='student') name= models.CharField(max_length=50) def __str__(self): return self.name trying to makemigrations -
Not able to do the migrate in Django, facing Attribute Error: 'str' object has no attribute '_meta'
I made a completely new project using the django-admin startproject and I also made an app using django-admin startapp and I am able to apply the initial migrations but not able to do the migrate. and I didn't add any code into the project. It's completely a new project. python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying auth.0013_user_following...Traceback (most recent call last): File "G:\My Drive\Django 4 by example\myshop\manage.py", line 22, in <module> main() File "G:\My Drive\Django 4 by example\myshop\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 448, in execute output = self.handle(*args, **options) File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 96, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\migrate.py", line 349, in handle post_migrate_state = executor.migrate( File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\executor.py", line 135, in migrate state = self._migrate_all_forwards( File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\executor.py", line 167, in _migrate_all_forwards state = self.apply_migration( File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\executor.py", line 252, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\migration.py", line 130, in apply operation.database_forwards( File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\operations\fields.py", line 108, in database_forwards schema_editor.add_field( File "C:\Users\admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\sqlite3\schema.py", line 383, in add_field if field.many_to_many and field.remote_field.through._meta.auto_created: AttributeError: 'str' object has no … -
How does one get a system-wide gunicorn to find django in a virtual environment?
Reading the gunicorn docs, I learn how to run gunicorn as a system-wide app managed via systemd. This is quite convenient, especially for managing multiple django apps via systemd. There is one problem that the documentation omits. It is that the django instances are most likely within virtual python environments. Here is what I get when I implement gunicorn's documentation: gunicorn[14780]: ModuleNotFoundError: No module named 'django' Not cool, not cool at all. I perceive that there is a way to get systemd services to cooperate with virtual environments but I can't seem to locate clear instuctions on that. Most articles out there would have me running gunicorn from the same virt environ with django. Does that mean I have to install a fresh virtual instance of gunicorn for every django project I create? -
Django Form modifies database, could it be an issue if two people submit a form at the same time
I'm very new to Django and I'm writing an app that gives user the best matching product from the database. I have a model with all the products and their specifications, model for user's preferences and Compatibility model where I have all the product ids and when user submits the form, compatibility column updates, then the table is sorted and gives back 5 top choices. My concern is if it could be an issue if two users submit a form at the exact same time? Could that cause User B getting top products for User A form? If yes, what would you recommend me to do or what to section in Django documentation could help me to figure it out? -
Queryset with entries that have related objects
I want to take all entries that have related objects class Author(models.Model): name = models.CharField(...) class Book(models.Model): author = models.ForeignKey(Author) I want to do a queryset that take all the authors that have at least one book. I did the logic in template to show only if _set.all.count != 0 like this views.py Author.objects.all() .html if author.books_set.all.count != 0 But the pagination is showing incorrectly -
How to update a User Profile in Django using Django REST API Framework?
【System Overview】 I have 5 different types of users (Administrators, Staffs, Clients, Students and Teachers) in my system. A client who owns his/her own profile can update his/her own profile information. He/she is not authorized to update other clients' profile information. I am not getting the output as expected as said above. models.py This file includes 2 models (UserAccount and ClientProfile) class UserAccount(AbstractBaseUser, PermissionsMixin): email = models.EmailField(verbose_name="Email Address", max_length=255, unique=True) full_name = models.CharField(verbose_name="Full Name", max_length=255) date_joined = models.DateTimeField(verbose_name="Member Since", auto_now_add=True) last_login = models.DateTimeField(verbose_name="Last Logged In", auto_now=True) is_verified = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_client = models.BooleanField(default=False) is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) is_active = models.BooleanField(default=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["full_name", ] objects = UserAccountManager() class Meta: db_table = 'USERS_INFORMATION' verbose_name = "Users Account" verbose_name_plural = "Users Accounts" def __str__(self): return self.full_name def get_name(self): return self.full_name def get_email(self): return self.email class ClientProfile(models.Model): class Meta: db_table = 'CLIENTS_PROFILE_INFORMATION' verbose_name = "Clients Profile Account" verbose_name_plural = "Clients Profile Accounts" client = models.OneToOneField(UserAccount, on_delete=models.CASCADE, related_name="client") country = models.CharField(verbose_name="Country", max_length=100, blank=True, null=True) is_client = models.BooleanField(default=True) def __str__(self): return self.client.full_name def get_email(self): return self.client.email def get_dateJoined(self): return self.client.date_joined def get_lastLoggedIn(self): return self.client.last_login def get_isVerified(self): return bool(self.client.is_verified) get_isVerified.boolean = True def … -
How to limit the number of results in a Django REST serializar?
Hi have this serializer: class ActivitiesSerializer(serializers.ModelSerializer): activity = serializers.CharField(source='task.name') project = serializers.CharField(source='project.name') discipline = serializers.CharField(source='task.discipline.name') class Meta: model = Activities fields = ( 'id', 'activity', 'project', 'discipline', ) How can I limit the number of results to 10? This is my view: class ActivitiesAPIView(generics.ListCreateAPIView): search_fields = ['task__name', 'task__discipline__name', 'project__name'] filter_backends = (filters.SearchFilter,) queryset = Activities.objects.all() serializer_class = ActivitiesSerializer -
how to count in django templates
Hi I am trying to count infringement inside templates. The results I am getting for 'a' the counter is 1 1 (two separate values) instead of total count of 2 or 1 1 1 instead of a total of 3. Please help as I am new to programming. html {% for infringer in page_obj %} <tr> <td>{{infringer.id}}</td> <td>{{infringer.created|date:"d M, Y"}}</td> <td>{{infringer.name}}</td> <td>{{infringer.brand_name}}</td> <td>{{infringer.status}}</td> <td> {% with a=0 %} {% for i in inc %} {% if infringer.id == i.infringer.id %} {{ a|add:"1" }} {% endif %} {% endfor %} {% endwith %} views.py > @login_required(login_url='login') def infringerlist(request): q= > request.GET.get('q') if request.GET.get('q') != None else '' > ings= Infringer.objects.filter(Q(created__icontains=q) | > Q(id__icontains=q) | > Q(status__name__icontains=q) | > Q(brand_name__icontains=q) | > Q(name__icontains=q), > customer=request.user.customer, > > ) paginator = Paginator(ings, 10) page_number = request.GET.get('page') page_obj = > paginator.get_page(page_number) > > inc = Infringement.objects.filter(customer=request.user.customer) context= {'page_obj': page_obj, 'inc': inc} return render(request, > 'base/infringers_list.html', context) -
Django rest framework nest two or more viewsets instead of mapping custom actions with @action decorator
So, lets pretend im trying to build an API for a tiny Chat application. Imagine i have 2 models in my Django project, one is for Messages and the other is for Groups. Each group can have multiple messages, but a message belows to only one Group (resulting in an one to many relationship). here are the models: class Group(models.Model): title = models.CharField(max_length=250) def get_messages(self): return self.messages.all() class Message(models.Model): body = models.TextField() group = models.ForeignKey(Group, on_delete=models.CASCADE, related_name="messages") And i have the following Django Rest Framework ViewSets: class GroupViewset(viewsets.ModelViewSet): queryset = Group.objects.all() serializer_class = GroupSerializer class MessageViewset(viewsets.ModelViewSet): queryset = Message.objects.all() serializer_class = MessageSerializer Viewsets are great! Only with those few lines i now have full CRUD operations for both Group and Message instances! I just need to access the following routes: /groups/ -> To make GET, POST operations for Group instances /groups/<group_pk>/ -> To make GET, PUT, PATCH, DELETE operations for Group instances /messages/ -> To make GET, POST operations for Message instances /messages/<message_pk>/ -> To make GET, PUT, PATCH, DELETE operations for Message instances but since a message belows to a Group, and i can get all messages of a group by doing GroupObject.get_messages(), im looking for a better way … -
Why do I keep getting an 'App not compatible with buildpack:' error when trying to deploy my django site to Heroku?
Here's the error: Building on the Heroku-22 stack -----> Using buildpack: heroku/python -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure ! Push failed I've been following YouTube tutorials. Nothing helps. I tried reading the Heroku docs. To no avail. Please help. Thank you! -
How to get Data from Working History Model to the Detail Staff? I am new on Django
I have two seperated models. One with fields of Staff and one for multiple Working History Contract. Now I want to display all the Working History Contract of One Staff data in Staff detail view. What do I have to change in the Staff Detail view and in Staff.html? models.py class Staff(models.Model): nu_identifikasaun = models.CharField(max_length=15, null=False, blank=False,verbose_name="Numeru Identifikasaun") nu_funsionariu = models.CharField(max_length=5, null=False, blank=False, default=0,verbose_name="identifikasaun Funsionariu") naran = models.CharField(max_length=30, null=False, blank=False,verbose_name="Naran Uluk") apelidu = models.CharField(max_length=100, null=True, blank=True,verbose_name="Naran Rohan (Apelidu)") sexu = models.CharField(choices=[('Mane','Mane'),('Feto','Feto')],max_length=10,null=True,verbose_name="Seksu") estadu_sivil = models.CharField(choices=[('Kaben Nain','Kaben Nain'),('Klosan','Klosan'),('Viuvu/a','Viuvu/a'),('Divorsiadu/Separadu','Divorsiadu/Separadu')],max_length=30,null=True,verbose_name="Estadu Sivil") fatin_moris = models.CharField(max_length=100, null=True, blank=True,verbose_name="Fatin Moris") data_moris = models.DateField(null=True,blank=True,verbose_name="Loron Moris") hela_fatin = models.CharField(max_length=100, null=True, blank=True,verbose_name="Hela Fatin") munisipiu = models.ForeignKey(Munisipiu, on_delete=models.CASCADE, null=True,related_name="Munisipiu",blank=True) kontaktu = models.IntegerField(null=True, blank=True,verbose_name="Numeru Telemovel") email_pessoal = models.EmailField(max_length=254,verbose_name="Email Pessoal") email_ofisial = models.EmailField(max_length=254,verbose_name="Email Ofisial") imajen = models.ImageField(upload_to='Funsionariu', null=True,blank=True,verbose_name="Fotografia") def __str__(self): #template = '{0.name}' return self.naran class Meta: verbose_name_plural='6-Dadus_Funsionariu_funsionariu' class ContractHistory(models.Model): funsionariu = models.ForeignKey(Staff, on_delete=models.CASCADE, related_name="funsionariuKSerbisu", verbose_name="Funsionariu") pozisaun = models.ForeignKey(Pozisaun, on_delete=models.CASCADE, null=True,related_name="Pozisaun",blank=True) salariu = models.CharField(max_length=100, null=True, blank=True,verbose_name="Salariu") kontratu_inisiu = models.DateField(null=True,blank=True,verbose_name="Hahu Kontratu") kontratu_remata = models.DateField(null=True,blank=True,default="",verbose_name="Kontratu Remata") divizaun = models.ForeignKey(Divizaun, on_delete=models.CASCADE, null=True,related_name="Divizaun",blank=True) departamentu = models.ForeignKey(Departamentu, on_delete=models.CASCADE, null=True,related_name="Departamentu",blank=True) tipu_kontratu = models.CharField(choices=[('Indeterminadu','Indeterminadu'),('Determinadu','Determinadu')],max_length=25,null=True,verbose_name="Tipu Kontratu") status_kontratu = models.BooleanField(default=True) obs_kontratu = models.TextField(max_length=255, null=True, blank=True,verbose_name="Observasaun") def __str__(self): template = '{0.funsionariu}' return template.format(self) class Meta: verbose_name_plural='7-Dadus_Funsionariu_kontratu-Serbisu' views.py def detailtaff(request,id): group = request.user.groups.all().all() data … -
Can't link my css file in my django project
This is a test im trying to do in order to link the file: first is the index.html file ``` `{% load static %} Document This is the Heading ` Second is the Settings file, i connected the css and the templates folders as well: notice! the name of my app is base which is mentioned in the installed apps from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-r*%-wq-%9jiwjznvwf$12m=286o5v_$)a6+1vc*_9hjq%nqh03' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'base' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'testpro.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR, 'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'testpro.wsgi.application' # Database # https://docs.djangoproject.com/en/4.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { … -
Should data in in json file 'structured using li tags?
[ { "model": "db.service", "pk": 1, "fields": { "catagory_name": "New host", "service_name": "<ul><li>Trip planning</li><li>Host shop</li></ul>" } }, { "model": "db.service", "pk": 2, "fields": { "catagory_name": "TOURING HOSTS", "service_name": "Tour of location" } and it has another 5 written like the second activity. This is shown on the front end as a drop down of the activities (service_name). However the tech lead wants me to show trip planning as a bulleted activity, like this **- Trip Planning Host Shop** All as one selection. In the front end code, the previous intern has used regex to seek the li and ul tags and replace them with || for some reason. He wants me to get rod of those which is easy enough, but I was wondering if I should keep the code to seek the tags and somehow make them into bullet points. I have tried replacing the || with & but get &&, I then try replacing && with & but that doesn't work and there are still || in the code, so I tried replaceAll. However this still doesn't get me bullet points. Front end is react. I tried putting the code in brackets with li tags and that didn't … -
Updating my live project to python 3.10 - ERROR python setup.py bdist_wheel did not run successfully
I've been having some trouble when trying to install certain packages on my live version of my project and realized its because its running version 3.7 instead of my up to date version 3.10. When I try to pip install -r requirements.txt I get a number of errors which I'm having no luck in fixing. installing mysql seems to be the reason for these errors appearing. ERROR1: python setup.py bdist_wheel did not run successfully. ERROR2: Running setup.py install for mysqlclient did not run successfully. ERROR3: error: command '/opt/rh/gcc-toolset-9/root/bin/gcc' failed: No such file or directory error: legacy-install-failure -
Django: Template does not exist
Please can you help me understand what I have done wrong here, I am sure it's a very simple problem but, I am new to django and especially the latest version... I believe and as far to my research that I have routed my views to the best of my knowledge, please may you help identify my issue, I am getting an error: "Page Not Found" url.py from my app from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index') ] views from my app from django.shortcuts import render from requests import request # Create your views here. def index(request): return render(request, 'landing_page/index.html') url from my project folder from django.contrib import admin from django.urls import path, include urlpatterns = [ path('/', include('comp.urls')), path('admin/', admin.site.urls), ] urls from my project and then here is my project and template folders, I have attached an image for your ease of helping me: