Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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;: … -
Simple JWT Method Not Allowed on Django App deployed on Gcloud App Engine
I am fairly new to django and gcloud and I am currently stuck at this issue where I am trying deploy my Django App on Gcloud App Engine. When accessing the api for getting token I got this error. Error when accessing API from App Engine from django.contrib import admin from django.urls import include, path from rest_framework_simplejwt import views as jwt_views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('quitnow/', include('quitnow.urls')), path("admin/", admin.site.urls), path('api/token/', jwt_views.TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh'), ] This is my urls.py. When I try to post my information to get token, the post requests doesn't return a response and hangs. I am stuck on this for days. Would really appreciate any help! -
The logic of if statement and (return redirect) in django
def set_default(request, id): Address.objects.filter(customer=request.user, default=True).update(default=False) Address.objects.filter(pk=id, customer=request.user).update(default=True) previous_url = request.META.get("HTTP_REFERER") if "delivery_address" in previous_url: return redirect("checkout:delivery_address") return redirect("account:addresses") This is a function that sets address to default and if the user came from checkout address page it sets default and return to same page.My question is about the logic of the if statment here.As far as I understand..If the condition is true return redirect("checkout:delivery_address") will be executed and it will exit the if condition then the last line will be executed return redirect("account:addresses") Why doesn't that happen and only the statment after if is executed when the condition is true? -
Best Python Framework suitable with Blockchain Database
As a side project, I have a web application idea, and I want to use Python at the backend. Firstly, I will use a conventional database. But after finishing the web application, I am planning to switch the database with a blockchain-based database like BigchainDB, or I will implement my blockchain. So my question is, which Python framework best suits this kind of database system? -
Update Django Formsets with data on many_to_many field
I feel like I've exhausted my google-fu on this subject. I've tried so many different ways, I can't remember what I've tried. I have a class "Recipe" which has 3 many_to_many fields. I've got an empty form using formsets for each many_to_many object for new. I'm now modifying the form to include "update", but I cannot seem to get the formsets to populate the data. I've tried "instance=", I've tried passing in a dictionary "model_to_dict", but I can't seem to figure this out. My current iteration looks like this: models.py: class Recipe(models.Model): def __str__(self): return self.name class Meta: unique_together = ('name', 'version') bs_file = models.FileField(storage=fs,null=True) name = models.CharField(max_length=75) dateCreated = models.DateField() dateUpdated = models.DateField(null=True, blank=True) version = models.IntegerField(null=True, blank=True) #type = models.CharField(max_length=30) #Cider, Mead, Wine, etc category = models.ForeignKey(BatchCategory,on_delete=models.CASCADE) brewer = models.CharField(max_length=30, null=True) batchSize = models.FloatField() #in Liters source = models.CharField(max_length=50, null=True) #Where did the recipe come from pairing = models.CharField(max_length=250, null=True) # Textfield listing various foods. TODO: Refactor notes = models.TextField() estOG = models.FloatField() estFG = models.FloatField() estABV = models.FloatField() fermentables = models.ManyToManyField(RecipeFermentable) adjuncts = models.ManyToManyField(RecipeAdjunct) yeasts = models.ManyToManyField(RecipeYeasts) You can see my 3 many_to_many fields at the bottom. views.py: def addRecipe(request,pk=None): if request.method == "GET": form = RecipeAddForm() … -
give a category using the action in django admin
can I use django actions to give a category to my articles? class Category(models.Model): name = models.CharField(max_length=155, db_index=True) class Woman(models.Model): title = models.CharField(max_length=255) content = models.TextField(blank=True) photo = models.ImageField(upload_to='img', blank=True) time_create = models.DateTimeField(auto_now_add=True) time_update = models.DateTimeField(auto_now=True) is_published = models.BooleanField(default=True) cat = models.ForeignKey(Category, on_delete=models.PROTECT,null=True) How can i create an action with the help of which it will be possible to give categories for several articles. I mean something like that https://docs.djangoproject.com/en/4.0/ref/contrib/admin/actions/ -
How to send emails from a contact form to recipient? Django
When I click the 'Send Message' button it gives me the message that it sent, but when I check my email the email is not there. Any help please? This is my first web application using Django. this is what it says in Git Bash after I send the message this is the index.html this is the views.py file this is the contact form, the contact form was made in index.html this is the settings.py file -
How to pass model instance pk to template from Django modelformset?
I have a model that I want to display in a template with a modelformset. I want to be able to delete instances of the model by pressing a button in the template, but I can't seem to pass the instance's pk. The "id" field only passes a huge boundfield that generates and error when I use it for the delete button. Is there any way to pass the instance's pk to the template? models.py class Activity(Model): user = ForeignKey(settings.AUTH_USER_MODEL, on_delete=CASCADE) activity = CharField(max_length=100, default='') number = IntegerField(default=1) def __str__(self): return self.activity Built in a formset: views.py activities = Activity.objects.filter(user=request.user) pre_formset = modelformset_factory(Activity, fields=('activity', 'number', 'id',)) formset = pre_formset(queryset=activities) template.html { formset.management_form }} {% for activity in formset %} {{ activity.id }} {{ activity.ORDER }} {{ activity.DELETE }} {% if not forloop.first %} <a class="btn" href="{% url 'activity_delete' activity.pk %}" onclick="return confirm('Are you sure you want to delete this activity?')">X</a> {% endif %} {% endfor %} -
json as table with django
I have modeled my database using models.py within my django project, one of the fields is a JSONField and I can save json data into that field without any problem. My doubt comes in how I can show that information as an html table. At the moment I have been using ListView to show that information in a template but I don't know how to transform it into a table. -
NGINX 403 (Forbidden) - Django React project
Hello i have problem with my Django React project .. i have 403 error on static files(js, css)..Error 403 NGINX Django