Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django fields help_text argument position in template
I have this code: class CreateListing(forms.Form): image = forms.CharField(label="Image URL", required=False, max_length=16384, help_text="Optional") Result is But is not nice UI arrangement. I want be same the↓: In Form Fields Documentation: The help_textarguments is wrapped in <span> element which is placed after <br> one. How setting Help_text final UI be same I want above? With grace arrangement. -
chat application using channels and django
I was following the tutorial on channels page https://channels.readthedocs.io/en/stable/tutorial/part_1.html but at the end of the second part the websocket should be working but in my case it says : WebSocket connection to 'ws://127.0.0.1:8000/ws/chat/g/' failed: and on the backend i get: [23/Feb/2023 17:01:28] "GET /chat/lobby/ HTTP/1.1" 200 1660 Not Found: /ws/chat/lobby/ [23/Feb/2023 17:01:28] "GET /ws/chat/lobby/ HTTP/1.1" 404 2226 when typing 'Hello' i should have got : Type the message “hello” and press enter. You should now see “hello” echoed in the chat log. -
How can I get the products from a main category and sub category in one view?
I have this product model: class Product(models.Model): type = models.CharField(max_length=20, choices=TYPES, default=SI) title = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE, default=None, related_name="products") body = models.TextField(max_length=5000, null=True, blank=True) image = models.FileField(upload_to=image_directory_path, default='products/default.png', null=True, blank=True) price = models.DecimalField(max_digits=20, decimal_places=2) length = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) width = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) height = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) weight = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) volume = models.DecimalField(max_digits=20, decimal_places=2, blank=True, null=True) sku = models.CharField(max_length=20, null=True, blank=True) stock = models.DecimalField(max_digits=30, decimal_places=0) user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="products") created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: verbose_name = "product" verbose_name_plural = "products" db_table = "products" def __str__(self): return self.title and this category model: class Category(models.Model): name = models.CharField(max_length=50) description = models.TextField(max_length=200, blank=True, null=True) parent = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True ,related_name='sub_categories') created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: verbose_name = "category" verbose_name_plural = "categories" db_table = "product_categories" unique_together = ('name', 'parent',) def __str__(self): return self.name def get_absolute_url(self): return self.slug At the moment I can only see the products from the category last in the hierarchy. If I go up to a parent category I cannot see any products. How can I get products from the parent (main category) and also … -
How to use csrf_token in Django RESTful API and React-Native?
I am trying to enable CSRF protection for a django - React Native application, I am familiar with the its process with React, from the django documentation at https://docs.djangoproject.com/en/3.1/ref/csrf/#ajax I get an error from if (document.cookie && document.cookie !== ""), is there an alternate way to enable the csrf apart from what is in this documentation or there is a change i need to make this piece of code function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); I am getting an error, with document -
Get attribute list after a django query filter
I have a WathList model: class Watchlist(models.Model): item = models.ForeignKey(Auction, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f"{self.user}\t\tItem: {self.item}" and I want to obtain all the item after performing a query def view_watchlist(request): active_listings = Auction.objects.filter(status=True) # watchlist_items = Watchlist.objects.filter(user=request.user).values('items') # for watchlist_item in watchlist_items: # print(watchlist_item.item) # print(watchlist_items.values('items')) return render(request, "auctions/index.html", { "listings": active_listings, }) to pass all the watchlisted items. Is it possible to make it without using a for loop? I tried to use .values method, .values_list and .only but did not work out: To make it work I created a empty list and a for loop def view_watchlist(request): watchlist_items = Watchlist.objects.filter(user=request.user).only('item') watchlist = [] for watchlist_item in watchlist_items: watchlist.append(watchlist_item.item) return render(request, "auctions/index.html", { "listings": watchlist, }) But I suspect there is a more elegant way to do it. Maybe using related_name when defining the model? -
Django rest unauthorize error even though that function not have any type of authentication
First of all whatever happening with me is very weired i have a django rest framework api and a nextjs frontend from the frontend i can call,login,signup,getProducts api but when i trying to call the verify otp route it is giving me unauthorize error even though that view have no authentication there as you can see from the server logs I can call the verify-otp by postman but when i am trying to call through nextjs it is giving the error here is the function from where i am calling the verify-otp ` ` export const handleVerifyOtp = async(otp,mobile_number) =>{ try { let data = { "otp":`${otp}`, "mobile_number":`${mobile_number}` } const response = await axios.post(`${API_URL}users/verify-otp/`,data); // dispatch(loginSuccess(response.data.data)); console.log("the response is",response.data) return response.data; } catch (error) { console.log("the error is",error) return error; } }`` In way to find solution i have checked every way i can find mistake here is python view which i am using there @api_view(['POST']) def verify_otp(request): print("GOT s") now = timezone.now() data = request.data otp = data['otp'] mobile_number = data['mobile_number'] -
In Django, querysets with multiple models evaluate very slowly
I have a Django project which I'm using to learn about optimizing searches in Django. I'm running Django 3.2 with a Postgres backend in a Docker container. I have two models, Chant and Sequence, which have the same fields, one view per model to search for instances of that model, and a combined search view, which searches for instances of both models and displays the results in a combined list. When I populate the database with a bunch of objects and try searching for things, the combined search view runs significantly slower than when searching for instances of a single model. Here are the relevant parts of my models.py: from django.db import models class Chant(models.Model): std_full_text = models.TextField(blank=True, null=True) class Sequence(models.Model): std_full_text = models.TextField(blank=True, null=True) Here is views/chant.py (views/sequence.py is the same, but with "sequence" and "Sequence" substituted for "chant" and "Chant"): from django.core.paginator import Paginator from django.views.generic import ListView from main_app.models import Chant class ChantSearchView(ListView): model = Chant template_name = 'chant_search.html' context_object_name = 'chants' paginate_by = 100 def get_queryset(self): query = self.request.GET.get('q') if query: return Chant.objects.filter(std_full_text__icontains=query) else: return Chant.objects.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) query = self.request.GET.get('q', '') page_number = self.request.GET.get('page', 1) paginator = Paginator(self.get_queryset(), self.paginate_by) page_obj = … -
Djnago - dynamically change order_by field (need to do it from swagger)
I've got a question. How to manage to change ordering thru the swagger. For example I've got a Menu model with fields: name and dishes. By GET I retrieve a list of menus and I would like to be able to choose in swagger if queryset should be ordered by name (alphabetically) or ordered by the numbers of dishes in menu (descending). I managed to do something similar with filtering the queryset: enter image description here But I can't find solution for switching the ordering. -
How to use PostgreSQL 9 with django?
Is there a way to use PostgreSQL version 9 with django framework? Must I downgrade my version of psycopg2? If yes which psycopg supports PostgreSQL 9? -
Issue with posting in GeoDjango
I'm trying to create an API that takes coordinates on a chart plane and is able to filter the data according to the width, length and the area of a counter box or wahtever emthod that the help me out. GeoDjango v3.2 looks like a good alternative to achieve this, also the djangorestframework-gis==1.0 package but when I try to use the post methos I get the error: "This field is required" this is the payload: import requests import json url = "http://127.0.0.1:8000/image/" payload = json.dumps({ "thickness": 1, "corners": { "type": "Point", "coordinates": [ 12.492324113849, 41.890307434153 ] } }) headers = { 'Content-Type': 'application/json' } response = requests.request("POST", url, headers=headers, data=payload) print(response.text) this is my model: from django.contrib.gis.db import models as gis_models from django.db import models from django.utils.translation import gettext_lazy as _ from django_extensions.db.fields import CreationDateTimeField, ModificationDateTimeField from hashid_field.field import HashidAutoField class ImageManager(models.Manager): pass class Image(models.Model): thickness = models.IntegerField(_("Thickness in [mm]")) corners = gis_models.PointField(_("Corners coordinates")) objects = ImageManager() class Meta: verbose_name: str = 'Image' THe serializer is: from hashid_field.rest import HashidSerializerCharField from rest_framework_gis.serializers import GeoFeatureModelSerializer, GeometryField from images.models import Image class ImageSerializer(GeoFeatureModelSerializer): corners = GeometryField(precision=2, remove_duplicates=True) class Meta(object): model = Image geo_field = 'corners' auto_bbox = True fields = '__all__' -
Django execute couple prefetch_related lookups in a single query
For now a I have not found an ability to execute reverse foreign key joins in Django more efficiently that using a prefetch_related a.k.a. joining in python. This method would generate 1 additional query for each reverse lookup and if I have 4-5 of those they start to decrease the performance and increase execution time. The only thing that is able to achieve that in one query is a full raw sql (not model.objects.raw()) which completely separates query results from the models (python objects) and leads to problems with drf serialization, fields renaming, testing and other stuff you can come up with. Does someone have an idea how to overcome this? Relation example: class Contest(models.Model): ... class Award(models.Model): contest = models.ForeignKey(Contest, related_name="awards") ... Contest.objects.prefetch_related("awards") # would generate 2 queries p.s. thanks in advance :) -
Django. ListView. The image attribute has no file associated with it
I'm new to Django, and I try to show the images of my model via the ListView class but keep getting the error "attribute has no file associated with it". Below is my code. model.py: from django.db import models class AboutModel(models.Model): person_name = models.CharField(max_length=128, null=True) person_position = models.CharField(max_length=128, null=True) person_photo = models.ImageField(upload_to='team_pictures', blank=True) views.py: from django.views import generic from . import models class AboutPage(generic.ListView): context_object_name = 'team_list' model = models.AboutModel app's urls.py: from django.urls import path from . import views app_name = 'app_main' urlpatterns = [ path('products_page/', views.ProductsPage.as_view(), name='products_page'), path('about_page/', views.AboutPage.as_view(), name='about_page'), path('contacts_page/', views.ContactsPage.as_view(), name='contacts_page'), ] project's urls.py: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from . import views urlpatterns = [ path('', views.HomePage.as_view(), name='index'), path("admin/", admin.site.urls), path('details/', include('app_main.urls', namespace='app_main')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) html: <div class='container team_members'> {% for member in team_list %} <img src={{ member.person_photo.url }}> <br>{{ member.person_name }} - {{ member.person_position }}<br> {% endfor %} </div> Solutions to similar issues on stackoverflow didn't help as custom function views are used there or the problem itself is different. -
Django taggit returns empty list of tags in search view
Explanation I would like to add to SearchView a filter that checks tags in my models and if raw_query contains tag then it displays the list of relevant objects. Each model contains title and tags fields. I am using django taggit with autosugest extension to handle tags in my application. For instance user is inserting tag1 into a search bar and MyModel1 contains a tag like this then it should appear on the page. If not then my SearchView is checking if rank returns anything and return list of relevant objects. Problem tag_query is always returning empty list. I checked database and tags are added correctly. I can display them in Django templates properly but my tag_query return empty list of tags. Question How can I implement tags filter properly so based on users query it will check list of tags and return objects that contain this tag. Code models.py from taggit_autosuggest.managers import TaggableManager class MyModel1(models.Model): title = models.CharField('Title', max_length=70, help_text='max 70 characters', unique=True) tags = TaggableManager() ... views.py class SearchView(LoginRequiredMixin, CategoryMixin, ListView, FormMixin, PostQuestionFormView): model = MyModel1 template_name = 'search/SearchView.html' context_object_name = 'results' form_class = PostQuestionForm def get_queryset(self): models = [MyModel1, MyModel2, MyModel3] vectors = [SearchVector(f'title', weight='A') + SearchVector(f'short_description', … -
Nginx not serving user-uploaded media(Image) files when Debug=False in settings.py
I have set up a django website that would be served by Nginx, everything was working perfectly not until images stopped showing recently. I tried inspecting the possible cause of this strange development using curl and then realized that the Content-Type is not recognized as Content-Type: image/jpeg returns a Content-Type: text/html; charset=utf-8 Below are my files : Variables in Settings.py STATIC_URL = '/home/ubuntu/static/' MEDIA_URL = "/home/ubuntu/media/" STATIC_ROOT = '/home/ubuntu/static' MEDIA_ROOT = '/home/ubuntu/media/' ONNGO_DOMAIN = "https://onngo.co.in" PROFILE_PICTURE_URL = MEDIA_ROOT+"profile_pictures/" STATICFILES_DIRS = ( os.path.join(CORE_DIR, 'apps/static'), ) Here is my full 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; types_hash_max_size 2048; # server_tokens off; server_names_hash_bucket_size 512; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # 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; #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/xml+rss text/javascript; ## # Virtual Host Configs ## include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/core; } #mail { # # See … -
how can I put existing django from my system to my new project
I created new python project and I find it difficult to reused my existing django module into my project I tried to write some cammand to include the django and it denied -
Return a list of options only if they exist in two Django Models
I have two models in my models.py file: Flavour model: class Flavour(models.Model): flavour_choice = models.CharField(null=True, blank=True, max_length=254) def __str__(self): return self.flavour_choice and Product model: class Product(models.Model): category = models.ForeignKey( 'Category', null=True, blank=True, on_delete=models.SET_NULL ) slug = models.SlugField() sku = models.CharField(max_length=254, null=True, blank=True) name = models.CharField(max_length=254) brand = models.TextField() has_flavours = models.BooleanField(default=False, null=True, blank=True) flavours = models.ForeignKey( 'Flavour', null=True, blank=True, on_delete=models.SET_NULL ) has_strength = models.BooleanField(default=False, null=True, blank=True) strength = models.ForeignKey( 'Strength', null=True, blank=True, on_delete=models.SET_NULL ) description = models.TextField() price = models.DecimalField(max_digits=6, decimal_places=2) rating = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=True) image_url = models.URLField(max_length=1024, null=True, blank=True) image = models.ImageField(null=True, blank=True) display_home = models.BooleanField(blank=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-created_at',) def __str__(self): return self.name I want to able to add flavours to the flavours table and then choose if they appear for particular products. How would I go about this? I know I could just add the flavours to the product but so many of the products I want to have, have the same flavours. I need to be able to do this database side and not just programmatically so admin users can add flavours and products via a front-end product management page. Any help would be greatly appreciated! -
Works well in Postman but not production
I want to display a variable generated in views.py in my login.html The views.py generates a username(voucher) and I want it auto filled in my login.html In the function the mpesa_body are details from a callback so it neither a GET nor POST. def confirmation(request): print("Start MpesaCallback") global profile, voucher mpesa_body = request.body.decode('utf-8') mpesa_body = json.loads(mpesa_body) print(mpesa_body) print("Mpesa Body") merchant_requestID = mpesa_body["Body"]["stkCallback"]["MerchantRequestID"] print('merchant_requestID: ', merchant_requestID) checkout_requestID = mpesa_body["Body"]["stkCallback"]["CheckoutRequestID"] print('checkout_requestID: ', checkout_requestID) result_code = mpesa_body["Body"]["stkCallback"]["ResultCode"] print('result_code: ', result_code) result_desc = mpesa_body["Body"]["stkCallback"]["ResultDesc"] print('result_desc: ', result_desc) metadata = mpesa_body["Body"]["stkCallback"]["CallbackMetadata"]["Item"] for item in metadata: title = item["Name"] if title == "Amount": amount = item["Value"] print('Amount: ', amount) elif title == "MpesaReceiptNumber": mpesa_receipt_number = item["Value"] print('Mpesa Reference No: ', mpesa_receipt_number) elif title == "TransactionDate": transaction_date = item["Value"] print('Transaction date: ', transaction_date) elif title == "PhoneNumber": phone_number = item["Value"] print('Phone Number: ', phone_number) str_transaction_date = str(transaction_date) trans_datetime = datetime.strptime(str_transaction_date, "%Y%m%d%H%M%S") tz_trans_datetime = pytz.utc.localize(trans_datetime) payment = MpesaPayment.objects.create( MerchantRequestID=merchant_requestID, CheckoutRequestID=checkout_requestID, ResultCode=result_code, ResultDesc=result_desc, Amount=amount, MpesaReceiptNumber=mpesa_receipt_number, TransactionDate=tz_trans_datetime, PhoneNumber=phone_number, ) if result_code == 0: payment.save() print("Successfully saved") password_length = 5 voucher = secrets.token_urlsafe(password_length) headers = { 'Content-Type': 'application/json', 'h_api_key': os.getenv("SMS_Token"), 'Accept': 'application/json' } payload = { "mobile": phone_number, "response_type": "json", "sender_name": "23107", "service_id": 0, "message": "Your WiFi Voucher is " + … -
Django get duration between now and DateTimeField
I have a Django model with the following field: date = models.DateTimeField('start date') I want to create a duration function that returns the duration between now and the date in the format "hours:minutes" How can we achieve this? -
400 (Bad Request) from Django Ajax sending Request
How to show simple message in ajax In below code url going to my view in the view else block but giving 400 bad request, when i am approving url is going to view and printing else message in coomand line but again giving 400 bad request function approveEmployeeTimesheet(emp_id) { //$("#approveTimesheet").off("click"); var yearMonth = $("#timesheetYearMonth").val(); bootbox.confirm("Are you sure you want to Approve ?", function (result) { if(result) { $.ajax({ url: "{% url 'user:Check_pending_request_approve_timesheet' %}", data: {"csrfmiddlewaretoken": "{{csrf_token}}", "year_month": yearMonth, "emp_id": emp_id}, dataType: "json", type: "POST", success: function(result) { $.ajax({ url: "{% url 'user:approve_employee_timesheet' %}", data: {"csrfmiddlewaretoken": "{{csrf_token}}", "year_month": yearMonth, "emp_id": emp_id}, dataType: "json", type: "POST", success: function(result) { // hide the edit, approve buttons. $("#approveTimesheet").hide(); $("#sendEditLink").hide(); $("#sendEditLinkApproveDiv").html("<div class='text-success' style='display:table;'><b><i class='fa fa-check'></i> Approved by "+result.timesheetApprovedBy+"</b></div>"); var myToast = Toastify({ text: "Timesheet Approved", duration: 3000, gravity: 'bottom' }); myToast.showToast(); getEmpTimesheets(emp_id) } }); }, error: function(err) { bootbox.alert("Please Approve/Reject the pending requests under tab"); } }); } }); } -
Django, how to cast base model to proxy model
I have a place in my code, where I need to overload model's property. For this matter I'm using proxy model of my base instance. models: class Question(TimeTrack): class Types(models.TextChoices): SINGLE_CHOICE = "SC", _("single_choice") MANY_CHOICE = "MC", _("many_choice") TRUE_FALSE = "TF", _("true_false") CHRONOLOGY = "CHR", _("chronology") MATCHING = "MCH", _("matching") position = models.PositiveIntegerField() text = models.CharField(max_length=512) image_src = models.CharField(max_length=256, blank=True, null=True) time = models.PositiveIntegerField() feedback = models.CharField(max_length=512) type = models.CharField(max_length=30, choices=Types.choices) quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) @property def answers(self): return self.answer_set.all() @property def correct_answers(self): return self.answer_set.filter(is_correct=True) def __str__(self): return f"Question #{self.id}" class ShuffledQuestion(Question): class Meta: proxy = True @property def answers(self): _answers = list(super().answers) random.shuffle(_answers) return _answers and the place where I create proxy: _question_data = model_to_dict(question) _question_data["quiz"] = question.quiz _question_data["group"] = question.group newQuestion = ShuffledQuestion(**_question_data) The above works just fine, but I wonder if there is "more elegant" way to accomplish the same. -
Ckeditor Image Properties how to modify this tab
I am trying to customize the Image Properties section of CKEditor, but I don't know where to access the properties to modify it. I refer to this screen here: The changes I seek are: make Upload default tab instead of Image Info Change Theme of this as it doesnt seem to use the skin I applied to actual rich text editor, as long as someone can point me to css behind it I can do the rest. Ability to actually modify width and height as they seem to be locked for some reason and I cant find property that handles it Set max width hard cap on images so they don't go above certain pixel amount. I use Django Python for reference. This is my custom config: CKEDITOR_CONFIGS = { 'default': { 'skin': 'light', 'removeDialogTabs': 'image:Link;image:advanced;', 'toolbar_Basic': [ ['Source', '-', 'Bold', 'Italic'] ], 'toolbar_YourCustomToolbarConfig': [ {'name': 'defaultstyle', 'items': ['Bold', 'Italic', 'Underline', 'Strike', 'TextColor', '-', 'Undo', 'Redo', '-', 'Link', 'Unlink', 'Anchor', '-', 'Image', 'Table', 'HorizontalRule', '-', 'Source', '-', 'Preview' ]}, '/', {'name': 'paragraph', 'items': ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl', 'Language']}, {'name': 'styles', 'items': ['Styles', 'Format', 'Font', 'FontSize']}, ], 'toolbar': 'YourCustomToolbarConfig', … -
Django, F object should be passed to my own function
I want to fetch leave requests of all employees where from date should be greater than each employees individual timezone. So i need to get Timezone and convert it to current employee timezone datetime. But im getting error that F object value is not passed as a value in to the function but as a F object. How to pass F object into the function or any solution to get current employee timezone and convert it to timezone current time? Thanks in advance LeaveRequest.objects.filter(from_date__gte=my_own_func(F('request__employee___user__timezone')) -
Django Postgresql dump file import export errors
After exporting database to sql file, it's impossible to import it again to database, it gives many syntax errors and Error in query (7): ERROR: schema "public" already exists I also tried removing all tables in database and it's not worked. How can I solve this issue? What is the best way to export and import database? Versions : Django 4, Postgresql 14.6 -
Testing Django data migrations. Tests pass, when ran solo, fail when ran in batch
Im trying to test data migrations, which include operations on two models: class Category(models.Model): title = models.CharField("Category title", max_length=100) def __str__(self): return self.title class Tag(models.Model): name = models.CharField("Tag", max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return f"{self.category}:{self.name}" The migrations: def add_tags_to_category_processes(apps, schema_editor): Category = apps.get_model("surveys", "Category") Tag = apps.get_model("surveys", "Tag") processes_category = Category.objects.get(title="Processes") tags_to_add = ("B2B", "EC", "Security", "Operations") for tag in tags_to_add: Tag.objects.create(name=tag, category=processes_category) class Migration(migrations.Migration): dependencies = [ ("surveys", "0049_change_location_users"), ] operations = [ migrations.RunPython(add_tags_to_category_processes), ] and def add_tag_to_category_external_hr_brand(apps, schema_editor): Category = apps.get_model("surveys", "Category") Tag = apps.get_model("surveys", "Tag") external_hr_brand_category = Category.objects.get(title="External HR Brand") tag_to_add = "External_Events" Tag.objects.create(name=tag_to_add, category=external_hr_brand_category) class Migration(migrations.Migration): dependencies = [ ("surveys", "0050_add_tags_to_category_processes"), ] operations = [ migrations.RunPython(add_tag_to_category_external_hr_brand), ] and finally tests: @pytest.mark.django_db def test_0050_add_tags_to_category_processes(migrator, settings): settings.ALLOWED_MIGRATIONS.append("0050_add_tags_to_category_processes") old_state = migrator.apply_initial_migration( ("surveys", "0049_change_location_users") ) Category = old_state.apps.get_model("surveys", "Category") Category.objects.create(title="Processes") new_state = migrator.apply_tested_migration( ("surveys", "0050_add_tags_to_category_processes") ) Tag = new_state.apps.get_model("surveys", "Tag") Category = new_state.apps.get_model("surveys", "Category") processes_category = Category.objects.get(title="Processes") # assert Tag.objects.filter(category=processes_category).count() == 4 tag_names = ("B2B", "EC", "Security", "Operations") assert ( all(Tag.objects.filter(name=name).exists() for name in tag_names) is True ) migrator.reset() @pytest.mark.django_db def test_0051_add_tag_to_category_external_hr_brand(migrator, settings): settings.ALLOWED_MIGRATIONS.append( "0051_add_tag_to_category_external_hr_brand" ) old_state = migrator.apply_initial_migration( ("surveys", "0050_add_tags_to_category_processes") ) Category = old_state.apps.get_model("surveys", "Category") Category.objects.create(title="External HR Brand") new_state = migrator.apply_tested_migration( ("surveys", "0051_add_tag_to_category_external_hr_brand") ) Tag = new_state.apps.get_model("surveys", … -
Main Container going blank
I am trying to make a home page in my Blog, but the template is messing everything up. The page only displays the navbar and the footer. What is wrong?? This is a screenshot of the home page. This is a link to the code. I have tried removing stuff, and changing it, but it still doesn't work.