Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Form Neither Shows Up nor Is It Integrated in The HTML
I'm trying to write a django form that works as a search bar, i've been following the tutorial i'm watching to the T, but for some reason when i run the code the form isn't there, and there's no trace of it in the HTML when i inspect it, it's as if i wrote nothing at all. below is the code i wrote in views.py, layout.html and the path in urls.py . It should be noted that this is the first time i work with django and so far it's been a bit confusing so please do check the code out and point out any and all bug(s). Thank You. Views.py from django import forms from django.shortcuts import render class searchForm(forms.Form): query = forms.CharField() def search(request): return render(request, "encyclopedia/entry.html", { "form": searchForm() }) layout.html <form action="{% url 'wiki:search' %}" method="post"> {{ form }} </form> urls.py from django.urls import path from . import views app_name = "wiki" urlpatterns = [ path("", views.index, name="index"), path("<str:title>", views.title, name="title"), path("<str:query>", views.search, name="search") ] -
How to group_by an annotated field for django querysets?
Hers is my model like this: class Article(models.Model): title = models.CharField(max_length=50, blank=True) author = models.CharField(max_length=50, blank=True) created_at = models.DateTimeField(auto_now_add=True) I want to return a queryset which is group_by created_at month, I annotated a created_month field for the queryset: queryset = Article.objects.annotate(created_month=TruncMonth('created_at')) but when I tried to group by created_at by adding .values('created_at'), like this: queryset = Article.objects.annotate(created_month=TruncMonth('created_at')).values('created_month').order_by('-created_month') The queryset returns only created_month field. What shall I do to get whole Article queryset group_by created_month like this: [ { 'created_month': '2021-07', 'articles': [ {'title': 'Article 1', 'author': ...} ] }, { 'created_month': '2021-06', 'articles': [ {'title': 'Article 2', 'author': ...}, {'title': 'Article 3', 'author': ...} ] } ] -
AttributeError: type object 'AuthorDetailView' has no attribute 'as_views'
I'm a beginner in python-django coding. Currently I am following this guide and doing the challenging part for the author page (https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Generic_views) but I am facing a issue of AttributeError: type object 'AuthorDetailView' has no attribute 'as_views'. Below are my codes: In urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('books/', views.BookListView.as_view(), name='books'), path('book/<int:pk>', views.BookDetailView.as_view(), name='book-detail'), path('authors/', views.AuthorListView.as_view(), name ='authors'), path('authors/<int:pk>', views.AuthorDetailView.as_views(), name='author-detail'), ] In views.py: from django.shortcuts import render # Create your views here. from .models import Book, Author, BookInstance, Genre def index(request): """View function for home page of site.""" # Generate counts of some of the main objects num_books = Book.objects.all().count() num_instances = BookInstance.objects.all().count() # Available books (status = 'a') num_instances_available = BookInstance.objects.filter(status__exact='a').count() # The 'all()' is implied by default. num_authors = Author.objects.count() context = { 'num_books': num_books, 'num_instances': num_instances, 'num_instances_available': num_instances_available, 'num_authors': num_authors, } # Render the HTML template index.html with the data in the context variable return render(request, 'index.html', context=context) from django.views import generic class BookListView(generic.ListView): model = Book paginate_by = 5 class BookDetailView(generic.DetailView): model = Book class AuthorListView(generic.ListView): model = Author paginate_by = 5 class AuthorDetailView(generic.DetailView): model = Author Would appreciate if someone can help me. Thank you -
How to solve InterFAX python library 400 error?
I've been working on a django project that needs to send faxes. For sending faxes I am using interfax python library. To generate pdf from html, I am using xhtml2pdf. I wrote like below, and it didn't work and threw an error. I don't know what to do now. Please help. The code # interfax authentication interfax_password = config("INTERFAX_PASSWORD") interfax_account = config("INTERFAX_ACCOUNT") interfax = InterFAX(username=interfax_account, password=interfax_password) f = File(interfax, pdf, mime_type="application/pdf") fax_number = config("INTERFAX_DESTINATION") # actually sending the data fax = interfax.outbound.deliver(fax_number=fax_number, files=[f]) The error thrown equests.exceptions.HTTPError: 400 Client Error: Bad Request for url:https://rest.interfax.net/outbound/faxes?faxNumber=111111111 Thank you in advance -
Django with websockets - Uvicorn + Nginx
I am trying to run a Django website with channels activated to use the websocket. Everything is working fine when using runserver, but things are getting spicy while switching to Nginx + Uvicorn. here is my /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=root Group=www-data WorkingDirectory=/home/myapp/ ExecStart=/usr/local/bin/gunicorn -w 1 -k uvicorn.workers.UvicornWorker --timeout 300 --bind unix:/home/myapp/myapp.sock myapp.asgi:application [Install] WantedBy=multi-user.target here is my /etc/systemd/system/gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/home/myapp/myapp.sock [Install] WantedBy=sockets.target and here is my /etc/nginx/sites-available/myapp server { listen 80; server_name myapp.box 10.42.0.1; location = /favicon.ico { access_log off; log_not_found off; } location ~ ^/static { autoindex on; root /home/myapp; } location ~ ^/ { include proxy_params; proxy_pass http://unix:/home/myapp/myapp.sock; } location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_buffering off; proxy_pass http://unix:/home/myapp/myapp.sock; } } Nginx is running, the socket and gunicorn too. but I have the following error while checking the gunicorn status Jul 07 11:14:11 hostname gunicorn[1825]: File "/usr/local/lib/python3.8/dist-packages/django/apps/registry.py", line 134, in check_apps_ready Jul 07 11:14:11 hostname gunicorn[1825]: settings.INSTALLED_APPS Jul 07 11:14:11 hostname gunicorn[1825]: File "/usr/local/lib/python3.8/dist-packages/django/conf/__init__.py", line 76, in __getattr__ Jul 07 11:14:11 hostname gunicorn[1825]: self._setup(name) Jul 07 11:14:11 hostname gunicorn[1825]: File "/usr/local/lib/python3.8/dist- packages/django/conf/__init__.py", line 57, in _setup Jul 07 11:14:11 hostname gunicorn[1825]: raise ImproperlyConfigured( Jul 07 11:14:11 … -
How to retrieve a list of objects (including ForeignKey Field data) in django (DRF) without significantly increasing DB call times
I have three models in a django DRF project: class ModelA(models.Model): name = .... other fields... class ModelB(models.Model): name = .... other fields... class ModelC(models.Model): name = .... model_a = FKField(ModelA) model_b = FKField(ModelB) I was using the default ModelViewSet serializers for each model. On my react frontend, I'm displaying a table containing 100 objects of ModelC. The request took 300ms. The problem is that instead of displaying just the pk id of modelA and ModelB in my table, I want to display their names. I've tried the following ways to get that data when I use the list() method of the viewset (retreive all modelc objects), but it significantly increases call times: Serializing the fields in ModelCSerializer class ModelCSerializer(serializers.ModelSerializer): model_a = ModelASerializer(read_only=True) model_b = ModelBSerializer(read_only=True) class Meta: model = ModelC fields = '__all__' Creating a new serializer to only return the name of the FK object class ModelCSerializer(serializers.ModelSerializer): model_a = ModelANameSerializer(read_only=True) (serializer only returns id and name) model_b = ModelBNameSerializer(read_only=True) (serializer only returns id and name) class Meta: model = ModelC fields = '__all__' StringRelatedField class ModelCSerializer(serializers.ModelSerializer): model_a = serializer.StringRelatedField() model_b = serializer.StringRelatedField() class Meta: model = ModelC fields = '__all__' Every way returns the data I need (except … -
How to use Django slugs creatively
In my frontpage.html. I have two buttons that link to the different categories of products I have I was using a for loop to get the slug needed for the URL link In the button, but this causes issues because it renders two buttons for each category i created in the models. My question: Is there a way for Django to only use one of these category slugs so I can specifically pick which URL it will render? I attached a picture of the frontpage.html file notice the for loop I am using to get the category slug that is being used to render the correct detail page. a for loop won't work since i have multiple categories HTML {% for category in menu_categories %} <a href="{% url 'category_detail' category.slug %}">Get Started</a> {% endfor %} models.py for categories class Category(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=255) ordering = models.IntegerField(default=0) Here is the models.py as well. I was thinking there should be a way to explicitly call a specific slug and not render both buttons right next to each other -
My form is not getting submitted in django. What's wrong with my code?
I am making a complaint management system but the page where I need to accept and save complaints from users, the form isn't even getting submitted as I can't even see the submitted message. models.py: class Complaint(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True) title = models.CharField(max_length=300) description = models.TextField(null=True, blank= True) highpriority = models.CharField(max_length=200, blank=True) document = models.FileField(upload_to='static/documents') def __str__(self): return self.title forms.py: PRIORITY_CHOICES= [ ('high', 'High'), ('low', 'Low'), ] class ComplaintForm(ModelForm): highpriority = forms.CharField(label='Priority', widget=forms.RadioSelect(choices=PRIORITY_CHOICES)) class Meta: model = Complaint fields = ['title', 'description', 'highpriority', 'document'] def clean(self): cleaned_data = super(ComplaintForm, self).clean() title = cleaned_data.get('title') description = cleaned_data.get('description') if not title and not description: raise forms.ValidationError('You have to write something!') template: <!-- Middle Container --> <div class="col-lg middle middle-complaint-con"> <i class="fas fa-folder-open fa-4x comp-folder-icon"></i> <h1 class="all-comp">New Complaint</h1> <form class="" action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-control col-lg-10 comp-title-field" name="title">{{form.title}}</div> <p class="desc">Description</p> <button type="button" class="btn btn-secondary preview-btn">Preview</button> <div class="Descr " name="description">{{form.description}}</div> {{message}} <button type="file" name="myfile" class="btn btn-secondary attach-btn"><i class="fas fa-file-upload"></i> Attachment</button> <button type="submit" name="submit" class="btn btn-secondary save-btn" value="Submit"><i class="fas fa-save"></i> Save</button> </form> </div> <!-- Right Container --> <div class="col right-pro-con"> <div class="img-cir"> <form method='POST' action="" enctype="multipart/form-data"> {% csrf_token %} {% if request.user.profile.profile_pic.url %} <img src={{request.user.profile.profile_pic.url}} alt="" … -
Multiple For Loops Django
I have the following two models ASPBoookings and Athlete. The Athlete model is linked to the ASPBookings model by the foreign key named athlete. I am trying to create a loop that will cycle through all of the bookings in the ASPBooking table and find out which is the most recent booking by each athlete. (the table can contain multiple bookings each to the same or different athletes (athlete_id) Once I have this information (booking_date and athlete_id) I then want to be able to automatically update the "Lastest ASP Session Field" in the Athlete Model. This is what I have tried so far. I can cycle through the bookings in the ASPBookings table and retieve and update the "Latest ASP Session Field" using the booking_date and athlete_id, but I cannot do this for multiple different athletes that are within the table. Currently the view just identifies the latest booking and the assigned athlete_id and then updates the field. Thanks in advance for any help. Below is the code. ASPBookings Model. class ASPBookings(models.Model): asp_booking_ref = models.CharField(max_length=10, default=1) program_type = models.CharField(max_length=120, default='asp') booking_date = models.DateField() booking_time = models.CharField(max_length=10, choices=booking_times) duration = models.CharField(max_length=10, choices=durations, default='0.5') street = models.CharField(max_length=120) suburb = models.CharField(max_length=120) region = … -
Django return HLS streaming to frontend
I have encountered an issue during develop HLS live streaming through Django restframework. Currently, I have a shell script that generates HLS files(m3u8), and now I am confused about how to respond the generated HLS files to the frontend so that the user able to view the HLS streaming from web. I did a little bit research on this, looks some developers suggest use Django serve, but I am confused will it be enough if I only return the m3u8 to the frontend. HLS source files generated from ffmpeg -
How to limit the pages to display using Django pagination module
I am trying to implement Django pagination on my page, and I don't want to show more than 5 pages at the same time. what I expect is, that when I click >> the next 5 pages are loaded so the user can click on it. But I don't know how I can do it so that when I click, the next 5 pages are displayed. For example, if the user clicks »: « 1 2 3 4 5 » Expected result: « 6 7 8 9 10 » Current result: « 1 2 3 4 5 » My code: index.html: {% for form in forms %} {% if forms.has_other_pages %} <ul class="nav nav-pills" id="evidence-formset-tab" role="tablist"> {% if forms.has_previous %} <li><a class="nav-link active" id="evidence-form-{{ forms.previous_page_number }}-tab" data-toggle="pill" href="#evidence-form-{{ forms.previous_page_number }}" role="tab" aria-controls="{{ aria_controls }}" aria-selected="true">&laquo;</a></li> {% else %} <li class="disabled"><span>&laquo;</span></li> {% endif %} {% for i in forms.paginator.page_range %} <li class="nav-item"> {% if forms.number == i %} <a class="nav-link active" id="evidence-form-{{ i }}-tab" data-toggle="pill" href="#evidence-form-{{ i }}" role="tab" aria-controls="{{ aria_controls }}" aria-selected="true">{{ i }}</a> {% elif i > forms.number|add:'-5' and i < forms.number|add:'5' %} <a class="nav-link" id="evidence-form-{{ i }}-tab" data-toggle="pill" href="#evidence-form-{{ i }}" role="tab" aria-controls="{{ aria_controls }}" aria-selected="false">{{ i }}</a> … -
Django Forum App, comments don't update on user-side, but can be seen through admin
For reference, here are my models in my Forum app: class Forum(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) description = models.TextField() created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('forum-detail', kwargs={'pk': self.pk}) class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) forum = models.ForeignKey(Forum, on_delete=models.CASCADE) description = models.TextField() created_at = models.DateTimeField(auto_now_add=True) To display the forum posts, I have a CBV 'ForumListView': class ForumListView(ListView): model = Forum template_name = 'forum/forum.html' context_object_name = 'forum_posts' ordering = ['-created_at'] From this list, the user can click on any forum and it will lead them to 'forum-detail' with the CBV 'ForumDetailView': class ForumDetailView(DetailView): model = Forum extra_context = { 'comments': Comment.objects.all().order_by('-created_at')} Here is where I passed in the comments from my Comment model to be shown alongside the post. I think this is the reason why the comments don't update, but I'm not too sure how to fix this. In the template for forum_detail.html, this is how I display all the comments made: {% for comment in comments %} {% if comment.forum == forum %} <div class="content-section"> <p>{{ comment.description }}</p> <small>{{ comment.user.username }}, on {{ comment.created_at|date:"F d, Y" }}</small> </div> {% endif %} {% endfor %} Note that the new comment made will be shown … -
Combined or get the Total value of the same fields using Django
I want to get the summary of data with in the same table. Get the duplicate value in "Changing Department" fields, changing department value are depends on the user input. Total the Product Quantity. The output will store in variable. How can I do that? Can you please drop any example for my reference?. Output are same as the picture below but I will display it using HMTL. Im using Django==3.2.3, and Python 3 Excel Sample Data -
In DJANGO, Is there a way to transfer the existing users in django.contrib.auth to SAML or OpenID?
I have used django-oidc-provider, but all it does is create a new user. For a large pre-existing user datatbase, it is inconvenient to create new accounts for all users. I want to do this because I cannot integrate AWS services into my django website without an industry standard for federated authentication. -
Using Swup with Django
My Issue: I am trying to use Swup Library with Django's templating engine and everything worked well; except for the fetching of new content. The animations worked perfectly; I could see my contents getting faded out. The addresses in which the get requests are fetching worked perfectly as well; I could see the HTTP response code of 200 being returned in my console. However, the main content, after being faded out, were not being replaced. An example of Django Renderings: Base URL: http://127.0.0.1:8000 <!-- What is written in my code --> <a href="{% url 'home_view' %}" > <!-- What Django renders in the browser --> <a href="/" > in my urls.py: urlpatterns = [ path('', views.homeView, name='home_view'), ] A worthy note: Using dev tools, when hovering over the href rendered, it shows http://127.0.0.1:8000/ Another strange thing I encountered when trying to debug was that my html element has the following attributes added to it but it stay there even after the animation ends. <html lang="en" class="swup-enabled is-changing is-leaving is-animating to-homepage"> Swup config or any additional relevant code used: let options = { LINK_SELECTOR: 'a', debugMode: true, }; const swup = new Swup(options); The Scripts loaded perfectly; I was able to … -
Adding Additional Data to a Serialize Response in Django
I've created a working post response of data from the model using ModelSerialzer, which I call from a post method in a view class. I would like to add additional data to the response. This is the pertinent code from my CBV: resource_data = Resources.objects.all() serializer = ResourceSerializer(resource_data, many=True) #serializer.data["service"] = "All Services" return Response(serializer.data) The commented out line was my attempt to add data base on a similar post here. I get a 500 response in my API call. What is the correct way to do it? The response data is JSON if that's necessary to mention. -
integrating ebay authentication in django application
I am building a django application in which user will be able to sign up or sign in only via their EBay account, no email/username or password required. I couldn't find any authentication library for EBay though there are many for google, facebook, twitter etc. So I got the EBay part working. EBay basically returns (on consent of user) Email and a IEFS token which is unique to that user and wont change. I want to use those two fields only to create a authenticate user across whole application. I don't want username, emails, firstname, lastname or password that ships with django User model. The documentation is quite big and I am confused where to start, any proper suggestion will be big help. Thank you. -
Django POST request not posting anything to database
I cloned Django free source code on GitHub and making modifications to it. The aim of my application is that I wrote an ML algorithm that predicts if one is to have diabetes or not. Here is my issue, the person made use of a single function that calls multiples pages through the help of Django loader. Now hitting on the submit button I want that function to run a submit based on the current page I am on. The function is shown below @login_required(login_url="/login/") def pages(request): context = {} # All resource paths end in .html. # Pick out the html file name from the url. And load that template. try: load_template = request.path.split('/')[-1] print(load_template) context['segment'] = load_template if request.method == "POST": print("YES") print(request.POST) person = Person(request.POST) print(person) person.name = request.POST.get("name") person.email = request.POST.get("mail") print(person.email) person.dob = request.POST.get("dob") person.gender = request.POST.get("gender") person.pregnancy = request.POST.get("Pregnancies") person.glucose = request.POST.get("Glucose") person.blood_pressure = request.POST.get("BloodPressure") person.skin_thickness = request.POST.get("SkinThickness") person.insulin = request.POST.get("Insulin") person.bmi = request.POST.get("BMI") person.pedigree = request.POST.get("DiabetesPedigreeFunction") person.age = request.POST.get("Age") print(person.save()) ml_pickled_model = "django-datta-able-master/ml/dataset/ml model.pkl" person_data = np.array( [ [ person.pregnancy , person.glucose , person.blood_pressure, person.skin_thickness , person.insulin , person.bmi, person.pedigree , person.age ] ] ).reshape(1,8) test_model = joblib.load(open(ml_pickled_model, 'rb')) prediction = test_model.predict(person_data) print(prediction) … -
I tried to delete admin user and then I can't login to the cyberpanel
I tried to remove the default admin user on cyberpanel as follows: Create a new user with the highest authority admin Login cyberpnael with new user and go to user section to delete admin user. I got an error message, I don't remember what it is. I cannot delete it. Then I click on edit and try to change Owner to new user. And as a result I get the error message: 500 Server Error. I went into SSH and edited /usr/local/CyberCP/CyberCP/settings.py to turn on debug. I received the following error message: Environment: Request Method: GET Request URL: https://myip:port/ Django Version: 3.1.3 Python Version: 3.6.8 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'baseTemplate', 'loginSystem', 'packages', 'websiteFunctions', 'tuning', 'serverStatus', 'dns', 'ftp', 'userManagment', 'databases', 'mailServer', 'serverLogs', 'firewall', 'backup', 'managePHP', 'manageSSL', 'api', 'filemanager', 'manageServices', 'configservercsf', 'pluginHolder', 'emailPremium', 'emailMarketing', 'cloudAPI', 'highAvailability', 's3Backups', 'dockerManager', 'containerization', 'CLManager', 'IncBackups', 'WebTerminal'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'CyberCP.secMiddleware.secMiddleware'] Traceback (most recent call last): File "/usr/local/CyberCP/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/CyberCP/lib/python3.6/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/CyberCP/lib/python3.6/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/usr/local/CyberCP/loginSystem/views.py", line 150, in loadLoginPage currentACL = ACLManager.loadedACL(userID) … -
I need to translate, or change "Please fill out this field" error message in UserCreationForm on Django
I have been trying and investigating a lot how to change just the error message, or just translate it to Spanish, but I do not manage to find quite the solution. I have tried using locale.Middleware on settings and adding the gettext to my Django project in order to translate it, no luck, here are the settings I am using: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] gettext = lambda x: x LANGUAGE_CODE = 'es' LANGUAGES = ( ('es', gettext('Spanish')), ) TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True After having those settings, and installing the gettext accordingly on my locale folder, no luck in translating the error messages. I have also tried on the forms.py changing the error_messages, but no luck, here is the code for the forms.py file (I have added 'required' everywhere just to see if the message slightly changes, no luck either, also I used 'required' and 'blank' neither worked): class CreateUserForm(UserCreationForm): first_name = forms.CharField(error_messages = {'required':"Ingrese su primer nombre"}, max_length=30,widget=forms.TextInput(attrs={'placeholder': 'Ingrese su nombre', 'class': "form-control"})) last_name = forms.CharField(error_messages = {'required':"Ingrese su segundo nombre"},max_length=30,widget=forms.TextInput(attrs={'placeholder': 'Ingrese su apellido', 'class': "form-control"})) password1 = forms.CharField( label="Password", error_messages = {'required':"Ingrese la … -
Django Get All Cookies With Name That Includes A Substring
I am making this simple random post system, and a problem I've been having is to recommend posts a user has not seen before. To differentiate a use who has seen a post and who has not seen a post, I store a cookie (for anonymous viewers) like so: def render_to_response(self, context, **response_kwargs): # Logic response.set_cookie(f'viewed{post_id}', 'true', max_age=60*60*24*10) # 30 Days Till Expiry This stores a cookie like if I have a post with id=12, it will be stored as: viewed12, true To get the value I do: request.COOKIES.get(f'viewed{post_id}') I want to know retrieve all cookies that begin with the string viewed and then I want to get everything after that (so I just want to get the id of the post from the cookie). This is my code: import random def random_post(request): objects_to_exclude = [1, 2, 8] # Using the cookies with substring "viewed" I want to insert into this list posts = Post.objects.all().exclude(pk__in=objects_to_exclude) post = random.choice(posts) return render(request, 'blog/post_detail.html', {'object': post, 'post': post, 'id': post.id, 'pk': post.id, 'random': 'True'}) Basically I want to find all the cookies with substring viewed, get the number after it, and then insert it into the list called objects_to_exclude. Edit: (I don't need … -
Rendering data to the templates Django
I'm trying to display the data from table using dynamic url. However, when I try to do so, it just rendered out the attribute of the table instead. But when I use the same syntax to print on the shell, it works here is my view def service_fait(request, my_id): if request.user.is_authenticated: elements = JobServices.objects.filter(id=my_id) for element in elements: print(element.service_name) print(element.hour) print(element.user) print(element.description) return render(request, 'services_faits.html', {'elements': elements}) else: return redirect('login') Here is the dynamic url: path('servicefait/<str:my_id>', views.service_fait, name='servicefait') And the template is: {% for tache in taches %}<a href="{% url 'servicefait' tache.id %}" class="btn btn-primary">Postuler</a>{% endfor %} Here is the output of the web page: element.service_name element.hour element.amount element.description And the shell is working properly as it shows the content of the above attribute And finally, here is the model: class JobServices(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) service_name = models.CharField(max_length=100, default="nom du service") hour = models.IntegerField(default="Heures") amount = models.FloatField(default="Cout") service_date = models.DateTimeField(auto_now_add=True, null=True) description = models.CharField(max_length=2000, null=True, default="annonce") image_url = models.CharField(max_length=2000, null=True, blank=True) image = models.ImageField(null=True, blank=True) -
Optional Subfactory
I would like to create a subfactory that only creates instances if the user requests it at call time. Given these models: class Group(models.Model): name = models.CharField() class Member(models.Model): name = models.CharField() group = models.ForeigKey(Group, blank=True, null=True) And this factory: class MemberFactory(factory.django.DjangoModelFactory): class Meta: model = Member name = factory.Sequence("Member {}".format) group = factory.Subfactory(GroupFactory) I would like the option of only creating a group if explicitly requested, but without losing all other features. In other words these should all work: MemberFactory() # Expect group=None MemberFactory(group=True) # Expect group=GroupFactory() MemberFactory(group__name="ABC") MemberFactory(group=Group.objects.get(...)) -
Issue with accents in Django
i've got the following code: <!DOCTYPE html> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <title>Página de prueba</title> </head> <body> <h1>Esto es una página de prueba</h1><br> Página de prueba para Python </body> </html> But, when i try to search it in any browser, this happens: Error What can I do? Thanks. -
How to query on values of foreign key in django
I have 4 models/tables. I am using Django's default SQLite database. Institutional User class InstituitionalUser(models.Model): fullName = models.CharField(max_length=50) postcode = models.CharField(max_length=50) email = models.CharField(max_length=50) password = models.CharField(max_length=50) Professional User class ProfessionalUser(models.Model): firstName = models.CharField(max_length=50) lastName = models.CharField(max_length=50) password = models.CharField(max_length=50) email = models.CharField(max_length=50) phone = models.IntegerField() Institute Open Positions class InstituteOpenPositions(models.Model): institueId = models.ForeignKey(InstituitionalUser, on_delete=models.CASCADE, related_name='institue') title = models.CharField(max_length=50) status = models.CharField(max_length=10) Work applications class ProfessionalWorkApplications(models.Model): workapplicant = models.ForeignKey(ProfessionalUser, on_delete=models.CASCADE, related_name='profworkapplicant') appliedJobs = models.ForeignKey(InstituteOpenPositions, on_delete=models.CASCADE, related_name='profappliedJobs') createdOn = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=10) Steps Institutional User can create a Job which is stored in Institute Open Positions table with Institute as a foreign key. Professional Users can see that job and Apply for that position. If they apply the action is getting stored in the Work applications table. In the Work applications table, I am storing reference of a ProfessionalUser who has applied for a position and the open position as appliedJobs. Now my question I want to write a query to get all the applications received for a given institute. In other words, I have Work applications table, I have mapped InstituteOpenPosition object and InstituteOpenPositions table has the Institue as a foreign key. I can say that I want to …