Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
On which tablet from the following can I code on?
I understand tablets are not a good choice for developers, but out of the following which one can be used for coding? (I'm pretty new at coding, so just some basic languages working should be fine.): SAMSUNG GALAXY TAB A7, Lenevo M10, or Lenevo Tab 4 tablet. Does any of these support mostly used languages and software? -
Django updating One-To-One Relationship is causing UNIQUE Constraint Failure
I cannot wrap my head around why I'm getting an error here - when the update query is run with this django ORM save() code, I get a UNIQUE Constraint Error: django.db.utils.IntegrityError: UNIQUE constraint failed: tasks_recurringtask.id From my understanding, update is executed immediately and only called on the same scheduler job that has the ID referencing the given RecurringTask. Maybe I'm missing something or there is a safe way to do this? Any explanations would be helpful, thanks! class RecurringTask(models.Model): name = models.CharField(max_length=255) owner = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='tasks') start_time = models.DateTimeField(default=now) scheduler_job = models.OneToOneField( Schedule, on_delete=models.CASCADE, blank=True, null=True, default=None ) def save(self, *args, **kwargs): # set all other dependencies for Task # update Scheduler Job if self.scheduler_job is None: self.scheduler_job = Schedule.objects.create(func='tasks.jobs.do_task', args=f'{self.pk}', next_run=self.start_time ) else: Schedule.objects.filter(id=self.scheduler_job_id).update( next_run=self.start_time ) super(RecurringTask, self).save(self) -
How to return last post?
I have probably a small problem. Namely how can i extract a last post when i use 'post.comments.all' class CommentPost(models.Model): user = models.ForeignKey(Profil, on_delete=models.CASCADE) post = models.ForeignKey(Posty, on_delete=models.CASCADE, related_name="comments") content1 = models.TextField(max_length=250, blank=False, null=False) date_posted = models.DateTimeField(default=timezone.now) date_updated = models.DateTimeField(auto_now=True) def __str__(self): return str(self.content1) Views tag = request.GET.get('tag') if tag == None: my_tag = Posty.objects.all print(my_tag) else: my_tag = Posty.objects.filter(created_tags__tag=tag) print(my_tag) If i tried use '[:1]' or last, this dont work. -
How can I get and display ForeignKey data in a Django template
I'm attempting to only display cards based on their category_name. for eg. I have 2 simple models, Product and Category: class Category(models.Model): category_name = models.CharField(max_length=254, blank=False, null=False) url_name = models.SlugField(max_length=254, unique=True) category_image = models.ImageField( null=False, blank=False, default='', upload_to='category_images', help_text='This will be the category image') category_description = RichTextField(default='') class Meta: verbose_name = 'Categories' def __str__(self): return self.category_name def get_category_name(self): return self.category_name class Product(models.Model): main_product_image = models.ImageField( null=False, blank=False, default='', upload_to='product_images', help_text='This will be the main image in the carousel.') alternative_image_1 = models.ImageField( null=True, blank=True, upload_to='product_images', help_text='This will be the first image in the carousel.') alternative_image_2 = models.ImageField( null=True, blank=True, upload_to='product_images', help_text='This will be the second image in the carousel.') category = models.ForeignKey( 'Category', null=True, blank=True, help_text='Assign product to category', on_delete=models.CASCADE) created_by = models.ForeignKey( User, on_delete=models.CASCADE, related_name='product_creator', null=True) sku = models.CharField(max_length=254, null=True, blank=True) name = models.CharField(max_length=254) product_display_description = RichTextField(default='') spice_rating = models.CharField(max_length=1, null=True, blank=True) has_sizes = models.BooleanField(default=False, null=True, blank=True) price = models.DecimalField(max_digits=10, decimal_places=2, default='0') add_to_carousel = models.BooleanField(default=False) in_stock = models.BooleanField(default=True) is_active = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = 'Products' ordering = ('-created',) def __str__(self): return self.name I would like to then display these product cards on the frontend based on their category names. Using something simple like … -
Make Column in Pandas Dataframe Clickable and pass text value to Django view
I have a column in a dataframe called State. I want it to be clickable and when clicked, go to a URL and pass the state name to a Django view. So far I have tried it this way: smalldf['state'] = smalldf['state'].apply(lambda x: f'<a href=".\?q={x}">{x}</a>') It creates a url like this: http://127.0.0.1:8000/mysite/?q=TN but I am unable to extract the value TN from inside the view. The Django code looks like this: print('state is : ') print(parm_state) search_form = DateRangeForm(request.POST or None) # if this is a POST request we need to process the form data if request.method == 'POST': date_from = request.POST.get('startDate') date_to = request.POST.get('endDate') I can find the TN state value at the top and can print it. But when I come back from the DateRangeForm the value is gone. I cannot find a way to access it from inside the if request.method == 'POST' code. Would appreciate some help. Thanks -
Created information box inside form, based on model fields
Greetings and Happy Christmas everyone! I'm trying to implement a simple information text based on my model field because it retains some data like: MyModel.information: { start_date: imaginary_date, end_date: imaginary_date, store_name: 'Foo bar' } Now I want to display inside my admin form that information as a text, like: 'Store Foo bar, start at imaginary_date and close at imaginary_date. That implementation is just to the client who is editing some information at the form, can see easily the information about the store. -
ImportError: cannot import name 'force_text' from 'django.utils.encoding' (/usr/local/lib/python3.9/site-packages/django/utils/encoding.py)
I get the error below when I add 'graphene_django' inside INSTALLED_APPS in the settings.py After running python3 manage.py runserver graphene_django is installed successfully using pip install django graphene_django This is full error that i get Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/Cellar/python@3.9/3.9.9/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/usr/local/Cellar/python@3.9/3.9.9/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 115, in inner_run autoreload.raise_last_exception() File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 381, in execute autoreload.check_errors(django.setup)() File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.9/site-packages/django/apps/config.py", line 223, in create import_module(entry) File "/usr/local/Cellar/python@3.9/3.9.9/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/usr/local/lib/python3.9/site-packages/graphene_django/__init__.py", line 1, in <module> from .fields import DjangoConnectionField, DjangoListField File "/usr/local/lib/python3.9/site-packages/graphene_django/fields.py", line 18, in <module> from .utils import maybe_queryset File … -
Fetching foreign key's tables data from primary key's table
These are my models: class Customer2(models.Model): Customer_Name=models.CharField(max_length=30) Customer_Address=models.CharField(max_length=100) Customer_Phone=models.IntegerField() Customer_Email=models.EmailField(max_length=50) class Meta: db_table="Customer_Table" class Product(models.Model): Product_Name=models.CharField(max_length=100) Quantity=models.FloatField(max_length=100) Comming_Date=models.DateField(max_length=15) Expire_Date=models.DateField(max_length=15) Comming_Price=models.FloatField(max_length=50) Picture=models.ImageField(upload_to='Images',blank=True, null=True) class Sale(models.Model): Customer=models.ForeignKey(Customer2, default=1, on_delete=models.CASCADE) Product=models.ForeignKey(Product, default=1, on_delete=models.CASCADE) Quantity=models.FloatField() Price=models.FloatField() Date=models.DateTimeField() Customer_Name1=models.CharField(max_length=20,default=0) Product_Name1=models.CharField(max_length=20,default=0) class Meta: db_table="Sale_Table" I want to get or fetch or show all Sale model( class Sale) data but instead of Customer and Product columns in Sale table(model),I want to show Customer_Name and Product_Name from their own tables what should I do? -
Custom format an inline formset
I'm create a template in Django, adding a form and formset to the template, but I don't like how it's formatting the formset by default. I've tried .as_table and .as_ul, but it's not formatting it to my liking. I'd like to see the following from the formset: Ingredient Percentage Delete ingredient1 .55 ingredient2 .22 ingredient3 .33 I've tried the code in "https://stackoverflow.com/questions/17492374/how-to-render-formset-in-template-django-and-create-vertical-table" but when I implement it, I'm getting two extra column, "ID" and "Recipe Name". I don't know where those columns are coming from and I don't know how to get rid of them. Example: models.py class Recipe(models.Model): name = models.CharField(max_length=200, null=True) description = models.CharField(max_length=200, null=True, blank=True) def __str__(self): return self.name class Recipe_Ingredient(models.Model): recipe_name = models.ForeignKey(Recipe, null=True, on_delete = models.SET_NULL) ingredient = models.ForeignKey(Product, null=True, on_delete= models.SET_NULL) recipe_percent = models.DecimalField(max_digits=8, decimal_places=5, blank=True) views.py def recipeUpdate(request, recipe_id): RecipeIngredientFormSet2 = inlineformset_factory(Recipe, Recipe_Ingredient, extra=10, fields=('ingredient', 'recipe_percent')) recipe = Recipe.objects.get(pk=recipe_id) formset = RecipeIngredientFormSet2(instance=recipe) context = {'formset' : formset} return render(request, 'accounts/recipe_form.html', context) recipe_form.html {% extends 'accounts/main.html' %} {% load static %} {% block content %} <div class="row"> <div class="col-md-6"> <div class="card card-body"> <form action="" method="POST"> {{ form }} <p></p> <!--{{ formset.as_table }}--> <p></p> {{ formset.management_form}} <!--{% for form in formset %} {{ form }} … -
500 Internal Server error FLASK in cs50 finance problem set
This is the error: 192.168.14.251 - - [29/Dec/2021 18:18:26] "GET / HTTP/1.0" 500 - Error on request: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/werkzeug/serving.py", line 323, in run_wsgi execute(self.server.app) File "/usr/local/lib/python3.9/site-packages/werkzeug/serving.py", line 312, in execute application_iter = app(environ, start_response) File "/usr/local/lib/python3.9/site-packages/flask/cli.py", line 338, in call self._flush_bg_loading_exception() File "/usr/local/lib/python3.9/site-packages/flask/cli.py", line 326, in _flush_bg_loading_exception reraise(*exc_info) File "/usr/local/lib/python3.9/site-packages/flask/_compat.py", line 39, in reraise raise value File "/usr/local/lib/python3.9/site-packages/flask/cli.py", line 314, in _load_app self._load_unlocked() File "/usr/local/lib/python3.9/site-packages/flask/cli.py", line 330, in _load_unlocked self._app = rv = self.loader() File "/usr/local/lib/python3.9/site-packages/flask/cli.py", line 388, in load_app app = locate_app(self, import_name, name) File "/usr/local/lib/python3.9/site-packages/flask/cli.py", line 240, in locate_app import(module_name) File "/home/ubuntu/finance/application.py", line 145 if len(rows) = 0: ^ SyntaxError: invalid syntax 192.168.14.251 - - [29/Dec/2021 18:18:26] "GET /favicon.ico HTTP/1.0" 500 - Error on request: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/werkzeug/serving.py", line 323, in run_wsgi execute(self.server.app) File "/usr/local/lib/python3.9/site-packages/werkzeug/serving.py", line 312, in execute application_iter = app(environ, start_response) File "/usr/local/lib/python3.9/site-packages/flask/cli.py", line 343, in call rv = self._load_unlocked() File "/usr/local/lib/python3.9/site-packages/flask/cli.py", line 330, in _load_unlocked self._app = rv = self.loader() File "/usr/local/lib/python3.9/site-packages/flask/cli.py", line 388, in load_app app = locate_app(self, import_name, name) File "/usr/local/lib/python3.9/site-packages/flask/cli.py", line 240, in locate_app import(module_name) File "/home/ubuntu/finance/application.py", line 145 if len(rows) = 0: ^ SyntaxError: invalid syntax This is my code: @app.route("/register", methods=["GET", … -
django-filters filter by Boolean field with DRF
I'm following the tutorial here: https://www.django-rest-framework.org/api-guide/filtering/#djangofilterbackend (specifically the django-filter-backend section) and I am unable to get this to work. My goal is to retrieve a list of "containers" that have the "in_use" field set to True, but it keeps returning all the records in the table. I can't really see what I am missing. I have added django-filters to my installed apps list and also added this to my REST_FRAMEWORK block: 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'] This is the API endpoint I'm trying to hit in postman: http://127.0.0.1:8000/displaydata/containers?in_use=True I've tried passing both 'True' and 'true', as well as 0s and 1s. views.py class ContainerViews(APIView): def get(self, request, id=None): if id: container = Container.objects.get(id=id) serializer = ContainerSerializer(container) return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) else: containers = Container.objects.all() serializer = ContainerSerializer(containers, many=True) filter_backends = [DjangoFilterBackend] filterset_fields = ['in_use'] return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) -
Can't reach local server while Django app is running
When I run python manage.py runserver I get Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). December 29, 2021 - 17:45:15 Django version 4.0, using settings 'webapp.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. but when I try to open it in Chrome I'm only getting ERR_CONNECTION_REFUSED. Only a few hours ago it worked, I changed nothing. -
i create two function for dispaly place and blog in my project(web site) but only one function displaying
views.py def fun(request): obj=place.objects.all( ) return render(request,"index.html",{'results':obj}) def func(request): obj=blog.objects.all( ) return render(request,"index.html",{'blogresults':obj}) urls.py urlpatterns = [ path('', views.fun, name='fun'), path('', views.func, name='func'), ] -
Django startproject fails: No module named zoneinfo
I am creating a new project in Django. My set up is Windows 10 Django 4.0 Python 3.8 On running django-admin startproject myproject, I recieve the following error: ... ModuleNotFoundError: No module named 'zoneinfo' During handling of the above exception, another exception occurred: ... ModuleNotFoundError: No module named 'backports' Any clues on how to resolve this issue? -
Django - How to register route with query parameters?
Im very new to Django, struggling to find the answer Im looking for. Please bear with me. In my app/urls.py file I have router = routers.DefaultRouter() router.register(r'drugs', views.DrugViewSet) In my views.py file I have class DrugViewSet(viewsets.ModelViewSet): queryset = Drug.objects.all().order_by('name') serializer_class = DrugSerializer And my DrugSerializer class looks like class DrugSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Drug fields = ('id', 'name', 'description', 'recommended_dose_mg', 'count', 'create_date', 'update_date') So when I do a GET on /drugs, I correctly get the list of drugs. And when I take a UUID (primary key) on a specific drug and do a GET on /drugs/<primary_key>, it correctly pulls the specific drug. However, I want the GET on /drugs/<primary_key> to display different data. I want to join it with another model that I have and return a new json response. How exactly would I do this? -
my chat app doesn't work after deployement - heroku django
I did a chatting part in my web app with django it works perfectly in local but after I deployed it to heroku , it doesn't work: this is my consumers.py class: from channels.generic.websocket import AsyncWebsocketConsumer from django.contrib.auth.models import User from django.db.models import Q from asgiref.sync import sync_to_async import json from chat.models import Thread, Message from users.serializers import UserSerializer class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): friend = None me = self.scope['user'] # logged in user friend_name = self.scope['url_route']['kwargs']['friend'] # get the username of that user, whoom you want to chat friend_instance = await sync_to_async(User.objects.get, thread_sensitive=True)(username=friend_name) # get user object of friend # create a new Thread object if thread of specific chat does not exists, otherwise return the thread thread = None try: thread = await sync_to_async(Thread.objects.get, thread_sensitive=True)((Q(user1=me) & Q(user2=friend_instance)) | (Q(user1=friend_instance) & Q(user2=me))) except: thread = await sync_to_async(Thread.objects.create, thread_sensitive=True)(user1=me, user2=friend_instance) self.room_name = thread.room_name # room name await self.channel_layer.group_add( self.room_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): ''' disconnect the websocket connection. ''' await self.channel_layer.group_discard ( self.room_name, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] from_user = text_data_json['user'] to_user = text_data_json['friend'] from_user_instanse = await sync_to_async(User.objects.get, thread_sensitive=True)(username=from_user['username']) # get user object of friend to_user_instanse = await sync_to_async(User.objects.get, … -
How to actually prove that the user consented to data processing while he submitted the form?
A user submits a form and opts in to receive a newsletter. What do I need to do to prove later that he actually did opt in? If I store submitted form data in a db table then I am able to manually create and modify entries, so I could just change his False to True and therefore db entries don't prove anything. I have a django website if it makes any difference. -
Django render_to_string Returns NoneType Error
Using Django Pagination I'm trying to do endless pagination using AJAX. I followed the example here: https://www.progerhub.com/tutorial/adding-pagination-with-infinite-scroll-in-django/ My view returns the first page of results just fine, but when I attempt to build the content for the additional pages and return it as JSON using render_to_string I get an error while appending data onto my content variable. error message web_1 | Traceback (most recent call last): ... web_1 | File "/usr/src/django/media/views.py", line 74, in get web_1 | content += render_to_string('media_item.html', {'media': media, }, request=request) ... web_1 | new_obj = func(obj, *arg_vals) web_1 | File "/usr/local/lib/python3.8/site-packages/django/template/defaultfilters.py", line 784, in divisibleby web_1 | return int(value) % int(arg) == 0 web_1 | TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' models.py class Media(Audit): title = models.CharField( max_length=255) description = models.CharField( max_length=500, blank=True, null=True) poster = ProcessedImageField( blank=True, null=True, format='JPEG', options={'quality': 100}, processors=[ResizeToFill(1000, 1500)], upload_to=get_poster_path) class Meta: ordering = ( 'title', 'year') def __str__(self): return self.title views.py class MediaView(LoginRequiredMixin, JsonMixin, View): def get(self, request, *args, **kwargs): context = self.get_context_data() media = models.Media.objects.filter() page = int(request.GET.get('page', 1)) p = paginator.Paginator(media, 24) # number of media per page # try to get media for the given page try: media_page … -
Docker with venv or without?
I am new in Docker and learning it, and my question is that do I have to use venv in Docker or isn't it important? Because I couldn't configure venv in docker, it gives me an error like cannot import Django activate venv..., I read some answers but couldn't get answer, some people say need to use venv others not important. My DOckerfile FROM python:3.8 #set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN python3 -m venv venv #Set work directory WORKDIR /code/ #Install dependencies COPY requirements.txt . RUN . /venv/bin/activate && pip install -r requirements.txt COPY . /code/ If I don't use venv Docker runs fine, but when it comes to install package it gives me warning like WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead:... Can someone explain clearly it? Thanks in advance -
django AttributeError when saving data with DRF
I have a problem when I make a POST. the entry is created (I can see it in django Admin panel) but DRF is throwing me an error AttributeError at /api/v1/reviews/ 'Review' object has no attribute 'review_score' review_score beeing a SerializerMethodField in serializer.py needed for the frontend (GET is working perfectly) model.py class Review(models.Model): company = models.ForeignKey(Company, related_name='company_review', on_delete=models.CASCADE) title = models.CharField(max_length=255) comments = models.TextField() validated = models.BooleanField(default=False) note_quality = models.DecimalField(max_digits=5, decimal_places=2) note_timing = models.DecimalField(max_digits=5, decimal_places=2) note_qualprix = models.DecimalField(max_digits=5, decimal_places=2) note_react = models.DecimalField(max_digits=5, decimal_places=2) note_followup = models.DecimalField(max_digits=5, decimal_places=2) note_clean = models.DecimalField(max_digits=5, decimal_places=2) created_at = models.DateField(auto_now_add=True) created_by = models.ForeignKey(User, related_name='created_review', on_delete=models.CASCADE) def __str__(self): return self.title views.py class ReviewViewSet(viewsets.ModelViewSet): serializer_class = ReviewSerializer queryset = Review.objects.all() def get_queryset(self): company_id = self.request.query_params.get('company_id', None) return self.queryset.filter(company_id=company_id, validated=True).annotate( review_score = Sum(F('note_quality')+F('note_timing')+F('note_qualprix')+F('note_react')+F('note_followup')+F('note_clean'))/6, ) def perform_create(self, serializer): obj = serializer.save(created_by=self.request.user) obj.save() serializer.py class ReviewSerializer(serializers.ModelSerializer): created_by = UserCreateSerializer(read_only=True) review_score = serializers.SerializerMethodField() def get_review_score(self, obj): rounded = round_up(obj.review_score, 0.5) return rounded class Meta: model = Review read_only_fields = ('created_at'), fields = ('id','company','title','comments','validated','note_quality','note_timing','note_qualprix','note_react','note_followup','note_clean','created_at', 'created_by', 'review_score') -
Django: How to add html tag from string to the html template
Details: Client framwork: Django Web server: Python + Flask I have an HTML page which rendered with a data array. Each item in the array contains some fields. And one of the fields is a json object. In order to improve the visibility of the json i've converted the json obj to html table. Currently it's does't work. The results (on the browser) looks like that: PasswordPolicy <table border="1"><tr><th>MinimumPasswordLength</th><td>16</td></tr><tr><th>RequireSymbols</th><td>True</td></tr><tr><th>Re Flask code: @app.route("/PasswordPolicy", methods=["GET"]) @login_required def get_password_policy(): get_table_content = list(db_object.get_password_policy()) search_event = request.args.get('searchquery') at_type = request.args.get('audittype') print("**************") for e in get_table_content: print("Before:") print(e['PasswordPolicy']) e['PasswordPolicy'] = json2html.convert(json = e['PasswordPolicy']) print("After:") print(e['PasswordPolicy']) print("get_table_content:") print(get_table_content[0]) print("**************") return render_template( 'soc2/password_policy.html', get_list=get_table_content ) Html content: <table id="datatable-buttons" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%"> <thead> <tr class="headings"> <th class="column-title">BusinessUnit </th> <th class="column-title">ControllerNumber </th> <th class="column-title">PasswordPolicy </th> </tr> </thead> <tbody> {% for elements in get_list %} <tr class="even pointer"> <td> {{ elements["BusinessUnit"] }} </td> <td> {{ elements["ControllerNumber"] }} </td> <td> {{ elements["PasswordPolicy"] }} </td> </tr> {% endfor %} </tbody> </table> The question is how to tell to the browser to parse the table as html instead of simple string -
Is it safe to delete a Django QuerySet that may be empty?
Is it safe to attempt to delete a QuerySet that might be empty? In other words, if I am not sure if the name "MJ" exists, is there any functional difference between these 2 approaches? Is either preferred? 1) query = m.objects.filter(name="MJ") if query.exists(): query.get().delete() m.objects.filter(name="MJ").delete() -
Django model, ImportError attempted relative import with no known parent package
I'm making a small Django app, and i just want to make some tests over the QuerySet of my model. However, when running code outside the manage.py runserver environment, i get this error : from .models import Article Error: ImportError: attempted relative import with no known parent package As already said, this works perfectly when making views, i can import my Article model and create Articles from the admin dashboard. My app structure looks like this: app/ admin.py apps.py models.py (this contains my Article model) views.py file_where_ihave_my_error.py -
Django NEWBIE - TemplateDoesNotExist
(My project directory is called test and the app in question is called posts) Django tried loading these templates, in this order: Using engine django: django.template.loaders.app_directories.Loader: /path-to-app-dir/virtual/test/posts/templates/index.html (Source does not exist) django.template.loaders.app_directories.Loader: /path-to-app-dir/virtual/platform/lib/python3.10/site-packages/django/contrib/admin/templates/index.html (Source does not exist) django.template.loaders.app_directories.Loader: /path-to-app-dir/virtual/platform/lib/python3.10/site-packages/django/contrib/auth/templates/index.html (Source does not exist) Views.py from django.shortcuts import render from django.http import HttpResponse def index(request): return render(request,'templates/index.html') Urls.py from django.urls import path from . import views urlpatterns=[ path('', views.index) ] I have mentioned the app in Settings.py so that probably shouldn't be an issue. What am I doing wrong ? -
Интеграция данных парсера с Django [closed]
Я хочу сделать сайт, на котором можно будет посмотреть информацию о разных вузах. У меня готовы парсеры, но я не понимаю, как можно правильно интегрировать парсеры в Django приложение... Когда я искал информацию по этому поводу, одним рекомендовали использовать django-admin команды, другим использовать парсеры. Я не понимаю, что использовать лучше, у чего какие плюсы и что стоит в итоге выбрать? На данный момент у меня парсеры заливают информацию в стороннюю бд и через класс вытягивается в html форму. Не думаю, что это правильное решение...