Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Taking in input calculating average using django
A person would type a number, django should be able to calculate average after each submission, 10000 estimated people who input a number, how do I achieve this. -
how to make a form field not part of the submitted form
I have an extra field in a django form that triggers javascript to change the fields in other forms: class MyForm(forms.ModelForm): my_extra_form_field = forms.ChoiceField() class Meta: model = MyModel fields = ["field1", "field2"] field_order = ["field1", "my_extra_form_field", "field2"] How can I ensure that my_extra_form_field is not included in the submiteed form? -
Bootsrap cards showing only vertically and not in a tabular format
Heres the code in html [Heres what is showing on the website][1] https://i.stack.imgur.com/5bB78.jpg > {% extends 'base.html' %} > > {% block content %} > <h1>Products</h1> > <div class="row"> > {% for product in products %} > <div class="col"> > <div class="card" style="width: 18rem;"> > <img src="{{ product.image_url }}" class="card-img-top" alt="..." width="300" height="300"> > <div class="card-body"> > <h5 class="card-title">{{ product.name }}</h5> > <p class="card-text">${{ product.price }}</p> > <a href="#" class="btn btn-primary">Add to Cart</a> > </div> > </div>[enter image description here][1] > </div> > {% endfor %} > </div> {% endblock %} -
Django project working fine in local host but making full of issues on hosting in c panel
I developed a website with django its working fine in local host.. but while hosting on c panel..static file issue cant link to another pagesnow only index page is working other pages its showing errer 404 -
Celery periodic task not showing in django table
Using Django 3.2 and celery to configure periodic tasks on AWS ECS. I have many periodic tasks which are running fine and created 2 new periodic tasks, but these tasks are not detected and not showing up in the Periodic Tasks table in Django admin The configuration I have is celery.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'qcg.settings') app = Celery('qcg') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() # Celery-beat-configuration CELERY_BEAT_SCHEDULE = { 'authentication-1': { 'task': 'authentication.periodic_task.clear_refresh_token', 'schedule': crontab(hour=23) }, 'authentication-2': { 'task': 'authentication.periodic_task.assistance_email_after_registration_task', 'schedule': crontab(hour=2) }, 'authentication-3': { 'task': 'authentication.periodic_task.send_reminder_email_before_deletion_task', 'schedule': crontab(hour=23) }, 'authentication-4': { 'task': 'authentication.periodic_task.delete_inactive_accounts_task', 'schedule': crontab(hour=23) } } The following two tasks are showing in the Periodic Tasks table authentication-1 authentication-2 While the other two tasks are not showing in the Period Tasks table and also not executing. The celery.py setting is as CELERY_RESULT_BACKEND = 'django-db' CELERY_TASK_DEFAULT_QUEUE = 'celery' CELERY_TASK_ACCOUNT_QUEUE = 'qcg-account-queue' CELERY_BROKER_URL = 'sqs://' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_TRACK_STARTED = True CELERY_RESULT_EXTENDED = True CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' CELERY_BROKER_TRANSPORT_OPTIONS = { 'visibility_timeout': 43200, 'polling_interval': 60 } And running the beat service as ["celery","-A","qcg","beat","-l","info","--pidfile","/tmp/celerybeat.pid"] and celery service as ["celery","-A","qcg","worker","-l","info","--concurrency","4"] -
Memurai not working with Django app in development with SSL
I'm building the Django app chat using Memurai. The app is in the development process, but I'm facing an issue. The issue is when I attach the SSL on development my chat not working. How can I configure Memurai with an SSL certificate? I will appreciate you if you guide me. -
Unable to subscribe to GCP Pub/Sub when running a server of Django application
I have a standalone python file and its subscribe to a topic and able to pull the message from the topic which is created in GCP. Would like to know, How do we initialize the subscription during python manage.py runserver ? Is it possible to avoid standalone file and include that in Django Project ? I am trying to add a subscription code in the manage.py file and getting error. def topic_subscription(): subscriber = pubsub_v1.SubscriberClient() project_id = "XXXXXXXXX" subscription_id = "XXXXXXXXXXXXX" subscription_path = subscriber.subscription_path(project_id, subscription_id) streaming_pull_future = subscriber.subscribe(subscription_path, callback="CallBackMethod in another app for processing") with subscriber: try: streaming_pull_future.result() except TimeoutError: streaming_pull_future.cancel() Error: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
Djago time widget not showing up
All I want to do is add time widget to my form so I can easily pick the time. Everything is very simple, the page is loading but the widgets don't show up. No error nothing. I am thinking maybe I didn't set up the form widgets correctly but not sure what I did wrong. Here is my Forms.py- from django.contrib.admin import widgets from django.contrib.admin.widgets import AdminDateWidget, AdminTimeWidget, AdminSplitDateTime class WorkOutForm(ModelForm): class Meta: model = WorkOut fields = '__all__' widgets={ 'start':AdminTimeWidget(), 'end':AdminTimeWidget(), } Here is the Models.py. You will notice "start" and "end" fields are timefield- class WorkOut(models.Model): date=models.DateField(auto_now_add=True, auto_now=False, blank=True) day=models.DateField(auto_now_add=True, auto_now=False, blank=True) start=models.TimeField(null=True) name=models.CharField(max_length=100, choices=move) weight=models.CharField(max_length=100, blank=True) rep=models.CharField(max_length=100, blank=True) pedal= models.CharField(max_length=100, blank=True) stretchtype =models.CharField(max_length=100, blank=True) end=models.TimeField(null=True) note=models.TextField(max_length=300, blank=True) def __str__(self): return self.name And here are the views linked to it even though I don't think it has much relevance- def workout(request): form=WorkOutForm() if request.method=="POST": form=WorkOutForm(request.POST) if form.is_valid(): form.save() context={'form':form} return render(request, 'myapp/enter_workout.html', context) def update_workout(request, pk): order=WorkOut.objects.get(id=pk) form=WorkOutForm(instance=order) if request.method=='POST': form=WorkOutForm(request.POST, instance=order) if form.is_valid(): form.save() context={'form':form} return render(request, 'myapp/enter_workout.html', context) And the form on HTML page is also very basic,so don't think there is any issue there either- <form action="" method="POST"> {% csrf_token %} {{form}} <input type="submit" value="Submit"> … -
Is this the fastest way to create a large list of model instances in Django that require an id lookup for a ForeignKey field?
Models class Foo(models.Model): name = models.CharField # ... class Bar(models.Model): foo = models.ForeignKey(Foo) # ... Is this the fastest way to create new instances of Bar given a list of Foo names? Or is there a way you can use foo's name in the creation of the Bar instance? to_create = [] for name in names: try: foo = Foo.objects.only('id').get(name=name).id except Foo.DoesNotExist: continue to_create.append(Bar(foo=foo, *other_fields)) Bar.objects.bulk_create(to_create) -
How to store variables in Django database field?
I've been trying to figure out if it's possible to store a variable in a Django database field. Here is an example: class Message(models.Model): message = models.TextField() And then in the HTML form field, someone inputs something like this: Hi {{ user.first_name }}, thanks for signing up to our {{ company.name }} newsletter. That then gets saved to the database, and when an email goes out, those fields are automatically populated with the appropriate data. Hope this makes sense. Thanks. -
How to create an admin inline for a recipe entry
I am creating a minimal viable product of a recipe application. I would like to leverage the admin site to create a diary entry that, consists of a recipe, that consists of ingredients with amounts and quantities. I read that inlines are possible. However, I have not successfully been able to implement one. class Meal(models.Model): id = models.BigAutoField(primary_key=True, editable=False) name = models.CharField(max_length=64, unique=True) class Meta: verbose_name = ("Meal") verbose_name_plural = ("Meals") def __str__(self): return f"{self.name}" class Measurement(models.Model): id = models.BigAutoField(primary_key=True, editable=False) name = models.CharField(max_length=64, unique=True) class Meta: verbose_name = ("Measurement") verbose_name_plural = ("Measurements") def __str__(self): return f"{self.name}" class Ingredient(models.Model): id = models.BigAutoField(primary_key=True, editable=False) name = models.CharField(max_length=64, unique=True) class Meta: verbose_name = ("Ingredient") verbose_name_plural = ("Ingredients") def __str__(self): return f"{self.name}" class Recipe(models.Model): id = models.BigAutoField(primary_key=True, editable=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=64) class Meta: verbose_name = ("Recipe") verbose_name_plural = ("Recipes") def __str__(self): return f"{self.name}" class RecipeIngredient(models.Model): id = models.BigAutoField(primary_key=True, editable=False) recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) quantity = models.CharField(max_length=64, blank=True, null=True) measurement = models.ForeignKey(Measurement, on_delete=models.CASCADE, blank=True, null=True) ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) class Meta: verbose_name = ("RecipeIngredient") verbose_name_plural = ("RecipeIngredients") class Diary(models.Model): id = models.BigAutoField(primary_key=True, editable=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) occured_at = models.DateTimeField() user = … -
Django - S3 - Access File Metadata
I have a simple model like so to store and track user uploaded documents: class Document(...): file = models.FileField(..., upload_to=upload_to) ... I am using the django-storage package to upload these files directly to s3. However, s3 is limited in what characters are allowed in file names. I want to preserve the original file name in the meta data of the uploaded file. I can easily set the meta data in my upload_to method, by I am having difficulty understanding how I can access this meta data without a hacky workaround. I like this process because I can see the original file name in S3 itself. def upload_to(instance, filename): """ custom method to control how files are stored in s3 """ # set metadata on uploaded file: instance.file.storage.object_parameters.update({ "Metadata" : { "original_name" : filename } }) ... The current solution I have is to use boto3 to grab the meta data, but is there a cleaner workaround? def _get_original_file_name(file_field): """ method to extract metadat from a file field """ # set up client: s3 = boto3.client('s3') # get head object: head_object = s3.head_object( Bucket=settings.AWS_STORAGE_BUCKET_NAME, Key=file_field.name, ) # extract meta data set in upload_to method: original_name = head_object['Metadata']['original_name'] return original_name One solution: … -
React Component not Refreshing Django REST
everyone ! I'm learning React by myself, and I'm stuck here where I'm doing a REST API for a Chat APP, when I POST a new message, the component don't refresh by itself, I have to refresh the page. I managed to refresh it putting the idmessage and vmessage in the useEffect array, but it kept hitting the API, and I'm pretty sure this wasn't supposed to happen. There may be a lot of wrong code here and a lot of different ways to do a better project, so I'm sorry if it's bad written. P.S: Everything is mocked for the first and second contact My MessagePage: const MessagesPage = () => { let [idmessage, setIdmessage] = useState([]) let [vmessage, setVmessage] = useState([]) useEffect(() => { getIdMessage() getVMessage() }, []) let url = 'http://127.0.0.1:8000' let getIdMessage = async () => { let response = await fetch(`${url}/api/messages/1/2/`) let data = await response.json() setIdmessage(data) } let getIdName = (idmessage) => { return idmessage.map((m) => ( m.contact.name )) } let getVName = (vmessage) => { return vmessage.map((m) => ( m.contact.name )) } let getVMessage = async () => { let response = await fetch(`${url}/api/messages/2/1/`) let data = await response.json() setVmessage(data) } const messages … -
nested serializer does not save nested fields
only the top-level table registers; models.py from django.db import models class FormularModel(models.Model): title = models.CharField(max_length=255, blank=False, null=False) created_by = models.IntegerField(blank=True, null=True) created_at = models.DateTimeField( db_column="creation_date", auto_now_add=True ) class Meta: app_label = 'my_data_base' db_table = "formular" class QuestionModel(models.Model): formular = models.OneToOneField(FormularModel, related_name='formular', on_delete=models.CASCADE,) title = models.CharField(max_length=255, blank=True, null=True) field_type = models.CharField(max_length=255, blank=True, null=True) update_by = models.IntegerField(blank=True, null=True) update_at = models.DateTimeField( db_column="my_data_base", auto_now_add=True ) class Meta: app_label = 'my_data_base' db_table = "question" class ResponseModel(models.Model): question = models.OneToOneField(QuestionModel, related_name='question', blank=True, null=True, on_delete=models.CASCADE,) values = models.CharField(max_length=255, blank=True, null=True) update_by = models.IntegerField(blank=True, null=True) update_at = models.DateTimeField( db_column="update_date", auto_now_add=True ) class Meta: app_label = 'my_data_base' db_table = "response" class FieldcontentModel(models.Model): questions = models.OneToOneField(QuestionModel, related_name='questions', on_delete=models.CASCADE,) values = models.CharField(max_length=255, blank=True, null=True) place = models.IntegerField(blank=False) update_by = models.IntegerField(blank=True, null=True) update_at = models.DateTimeField( db_column="update_date", auto_now_add=True ) class Meta: app_label = 'my_data_base' db_table = "field" serilizers.py from .models import * from rest_framework import serializers from drf_writable_nested.serializers import WritableNestedModelSerializer class ResponseSerializer(serializers.ModelSerializer): class Meta(): model = ResponseModel fields = ['id', 'values'] class FieldSerializer(serializers.ModelSerializer): values = serializers.CharField() place = serializers.CharField() class Meta(): model = FieldcontentModel fields = ['id', 'values', 'place'] class QuestionSerializer(serializers.ModelSerializer): title = serializers.CharField() field_type = serializers.CharField() fieldcontent = FieldSerializer(many=True, allow_empty=False) response = ResponseSerializer(many=True, allow_empty=False) class Meta(): model = QuestionModel fields = … -
creating object for django model
a model is created for orders and one for order items.when we create an order via the views why 'user_id' is when the field name in the model is just 'user' models.py class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="order_user") views.py order = Order.objects.create( user_id=user_id, Similar happened with orderitems models.py class OrderItem(models.Model): order = models.ForeignKey(Order, related_name="items", on_delete=models.CASCADE) views.py for item in basket: OrderItem.objects.create(order_id=order_id, product=item["product"], price=item["price"], quantity=item["qty"]) full code order/models.py from decimal import Decimal from django.conf import settings from django.db import models from store.models import Product class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="order_user") full_name = models.CharField(max_length=50) email = models.EmailField(max_length=254, blank=True) address1 = models.CharField(max_length=250) address2 = models.CharField(max_length=250) city = models.CharField(max_length=100) phone = models.CharField(max_length=100) postal_code = models.CharField(max_length=20) country_code = models.CharField(max_length=4, blank=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) total_paid = models.DecimalField(max_digits=5, decimal_places=2) order_key = models.CharField(max_length=200) payment_option = models.CharField(max_length=200, blank=True) billing_status = models.BooleanField(default=False) class Meta: ordering = ("-created",) def __str__(self): return str(self.created) class OrderItem(models.Model): order = models.ForeignKey(Order, related_name="items", on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name="order_items", on_delete=models.CASCADE) price = models.DecimalField(max_digits=5, decimal_places=2) quantity = models.PositiveIntegerField(default=1) def __str__(self): return str(self.id) checkout/views.py def payment_complete(request): PPClient = PayPalClient() body = json.loads(request.body) data = body["orderID"] user_id = request.user.id requestorder = OrdersGetRequest(data) response = PPClient.client.execute(requestorder) total_paid = response.result.purchase_units[0].amount.value basket = Basket(request) order = Order.objects.create( user_id=user_id, … -
Python converting Django model.datetime from 24hr to AM/PM?
So I have this model field in Django that stores time in YYYY-MM-DD HH:MM:SS, here is how its created. station_0_checked_time = models.DateTimeField( null = True, default = datetime.datetime(1970, 1, 1, 0, 0) ) The data is stored properly as verified by the admin section of my Django site. Station 0 Checked Time: Date: 1970-01-01 Time: 22:00:10 However, when attempting to retrieve the data in a Django view with the following code I get the wrong output #SUBCARD is the name of the model object print(SUBCARD.station_0_checked_time) Expected: 1970-01-01 22:00:10 Actual: 1970-01-02 06:00:10+00:00 I don't really understand the conversion that is happening here. Thank you for the help. -
Form Validation not happening for Django model form
I have created the following model form and I want to apply validation on it but it is not working. Can anyone please tell me what mistake I am making? """class used for booking a time slot.""" class BookingForm(forms.ModelForm): class Meta: model = Booking fields = ['check_in_date', 'check_in_time', 'check_out_time', 'person', 'no_of_rooms'] """Function to check if username and password match or not.""" def clean(self): cleaned_data = super().clean() normal_book_date = cleaned_data.get("check_in_date") normal_check_in = cleaned_data.get("check_in_time") if (normal_book_date < now.date() or (normal_book_date == now.date() and normal_check_in < now.time())): #self._errors['check_in_date'] = self.error_class([ # 'You can only book for future.]) raise ValidationError( "You can only book for future." ) return cleaned_data -
Django: Custom PasswordResetForm issues
I have looked over other answers and questions and nothing I do seems to be working any suggestions on why this is not working. My custom class is not overiding and taking on a class or placeholder. I would like to try to get this set up to clean it up on my html to match my theme. My only thought might be the way I am using the url Path not being right how ever with my custom view reference it I dont know how to implement this properly. Form: from django.contrib.auth.forms import PasswordResetForm class UserPasswordResetForm(PasswordResetForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Override the email widget self.fields['email'].widget = forms.TextInput( attrs={'class': 'form-style', 'type': 'email', 'required': 'required', 'placeholder': 'Email'}) View: def password_reset_request(request): if request.method == "POST": password_reset_form = UserPasswordResetForm(request.POST) if password_reset_form.is_valid(): data = password_reset_form.cleaned_data['email'] associated_users = CustomUser.objects.filter(Q(email=data)) if associated_users.exists(): for user in associated_users: subject = "Password Reset Requested" email_template_name = "members/password_reset_email.txt" c = { "email":user.email, 'domain':'127.0.0.1:8000', 'site_name': 'Website', "uid": urlsafe_base64_encode(force_bytes(user.pk)), "user": user, 'token': default_token_generator.make_token(user), 'protocol': 'http', } email = render_to_string(email_template_name, c) try: send_mail(subject, email, 'admin@example.com', [user.email], fail_silently=False) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect("/password_reset/done/") password_reset_form = PasswordResetForm() return render(request=request, template_name="members/password_reset.html", context={"password_reset_form": password_reset_form}) Template: {% extends 'members/base.html' %} {% block … -
Filter by multiple years in DRF
So I'm trying to do filter by year and so it could use multiple values like this filter?year=2000,2021 And with this I should get all objects with year 2000 or 2021 My filter.py from django_filters import( BaseInFilter, NumberFilter, FilterSet, CharFilter, ) from .models import Research class YearInFilter(BaseInFilter, NumberFilter): pass class ResarchFilter(FilterSet): year = YearInFilter(field_name='date', lookup_expr='year') category = CharFilter(field_name='category', lookup_expr='iexact') class Meta: model = Research fields = ['date', 'category'] It looks almost like example from django-filter. But when I'm trying to use it i've got an error Field 'None' expected a number but got [Decimal('2000'), Decimal('2021')]. So what's wrong here? Why here is Decimal? Why it's not number? And how make it work like expected? -
AttributeError: partially initialized module 'posts.views' has no attribute 'SearchMenuPage' (most likely due to a circular import)
I'm attempting to emulate the url routing of StackOverflow when it comes to requesting a URL with the path of search/. As shown, requesting that URL redirects to search?q=. Yet the following error is being raised when running the test to achieve the aforementioned result: AttributeError: partially initialized module 'posts.views' has no attribute 'SearchMenuPage' (most likely due to a circular import) Within the RedirectView, I set the url attribute to an f-string that interpolates reverse_lazy(). https://docs.djangoproject.com/en/4.1/ref/urlresolvers/#reverse-lazy What is the cause of this error and what would be the appropriate fix? class TestRedirectSearchView(TestCase): def setUp(self): self.request_url = reverse('posts:search_menu') self.response_url = f"{reverse('posts:search_results')}?q=" def test_search_page_response(self): response = self.client.get(self.request_url, follow=True) self.assertRedirects(response, self.response_url) posts_patterns = ([ path("", pv.QuestionListingPage.as_view(), name="main"), re_path(r"questions/?", pv.AllQuestionsPage.as_view(), name="main_paginated"), re_path(r"questions/ask/?", pv.AskQuestionPage.as_view(), name="ask"), re_path(r"questions/<question_id>/edit/?", pv.EditQuestionPage.as_view(), name="edit"), re_path("questions/<question_id>/edit/answers/<answer_id>/?", pv.EditPostedAnswerPage.as_view(), name="answer_edit"), re_path("questions/<question_id>/?", pv.PostedQuestionPage.as_view(), name="question"), re_path(r"questions/search/", pv.SearchMenuPage.as_view(), name="search_menu"), re_path(r"questions/search", pv.SearchResultsPage.as_view(), name="search_results"), path("questions/tagged/<tags>", pv.TaggedSearchResultsPage.as_view(), name="tagged") ], "posts") class SearchMenuPage(RedirectView): url = f"{reverse_lazy('posts:search_results')}?q=" class SearchResultsPage(PaginatedPage): def get(self, request): query, tab_index = request.GET.get('q'), request.GET.get('tab', 'newest') queryset, query_data = Question.searches.lookup(tab_index, query=query) if query_data['tags'] and not query_data['title'] and not query_data['user']: tags = "".join([ f"{tag}+" if i != len(query_data["tags"]) - 1 else f"{tag}" for i, tag in enumerate(query_data["tags"]) ]) return HttpResponseRedirect(reverse("posts:tagged", kwargs={'tags': tags})) else: context = super().get_context_data() search_value = "".join(list(reduce( lambda main_string, … -
Even guincorn is installed, Package 'gunicorn' is not installed, so not removed
I want to remove guincorn completely from my ubuntue server. However, when trying to run sudo apt-get purge --auto-remove gunicorn . it says Package 'gunicorn' is not installed, so not removed. Here is a screen shot which shows gunicorn is installed. How can I complete remove guincorn from my server? -
My django admin search list page view distorted
Is anyone know how to fix this css issue getting distorted see screenshot this is the screenshot of distorted -
How to count reviews for a product in django?
I am building an ecommerce website with django. In my models I have a Product and review model. How should i connect the two for the number of reviews and average rating attribute? This is my current models file class Product(models.Model): name = models.CharField(max_length=200, null=True, blank=True) brand = models.CharField(max_length=200, null=True, blank=True) image = models.ImageField(null=True, blank=True, default='placeholder.png') description = models.TextField(null=True, blank=True) rating = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True) price = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True) countInStock = models.IntegerField(null=True, blank=True, default=0) id = models.UUIDField(default=uuid.uuid4, max_length=36, unique=True, primary_key=True, editable=False) numReviews = [Count the number of reviews where product.id matches self.id] averageRating = [Sum up the ratings in reviews for this product and divide them by their count] def __str__(self): return str(self.name) class Review(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) rating = models.IntegerField(null=True, blank=True, default=0) comment = models.TextField(null=True, blank=True) createdAt = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, max_length=36, unique=True, primary_key=True, editable=False) def __str__(self): return f'{self.user} review for {self.product}' As you can see the numReviews and average rating columns are meant to connect both tables. I have been trying to figure out how to do it correctly with no success. Any help would be greatly appreciated -
Why is my function get_absolute_url is merging my domain into my website name?
I'm using the Django sitemap framework, and I have to use the function get_absolute_url to render the site URL in the sitemap. However, I'm facing a problem because my link is becoming: exampleio.io instead of example.io. My function in my model is it: def get_absolute_url(self): return reverse('packages', args=[self.name]) My function in the sitemap.py class ExampleSitemap(Sitemap): protocol = "https" changefreq = "weekly" priority = 0.7 limit = 500 def items(self): return Example.objects.all() I'm getting: <sitemap> <loc>http://exampleio.io/sitemap-examples.xml</loc> </sitemap> -
how to convert my html string into its own datatype?
I'm fairly new to JS and HTML, Working on a Django project now makes me crazy about it . I have passed a variable from context from Django toward html. I noticed the datatype of the data is converted to string by defualt. views.py: context = {'segment': 'index', "service_data": data } html_template = loader.get_template('index.html') return HttpResponse(html_template.render(context, request)) HTML pages <div class="card-body"><canvas id="myAreaChart" width="100%" height="40"></canvas></div> <script type="text/javascript"> const service_data = "{{ service_data }}" </script> In Javasript, I can see the datatype of service_data is string. I'd like to traverse it as a array, but it is converted to string. const data = Array.from(service_data); //this is converted to objet not arrary.. function prepareChartData(data) { var chartData = []; for (var i = 0; i < 10; i++) { let timestampe = data[i][0] let dat_list = data[i][1] chartData.push([timestampe, dat_list]); My service_data is a fairly large data from django backend, hence, I do not want to use split or something to convert it. The service_data snipet: Please ignore those &gt, etc, not sure why HTML added them, but image the data itself is a very nested dictnary. [(datetime.datetime(2022, 10, 4, 18, 35, 1, 247336, tzinfo=&lt;UTC&gt;), [[{&#x27;kubernetes_pod_name&#x27;: &#x27;kafka-rawbus-bravo-3&#x27;, &#x27;value&#x27;: 7.5456592756413645}, {&#x27;kubernetes_pod_name&#x27;: &#x27;kafka-rawbus-bravo-5&#x27;, &#x27;value&#x27;: 6.988051860579239}, {&#x27;kubernetes_pod_name&#x27;: …