Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'method' object does not support item assignment
I am trying to count likes on each post and this is my model. But I am getting error on the item detail page likes = models.ManyToManyField(User, related_name='blog_posts') def total_likes(self): return self.likes.count() VIEW: class ItemDetailView(DetailView): model = Item template_name ='waqart/item_detail.html' def get_context_data(self, *args, **kwargs): context = super(ItemDetailView, self).get_context_data stuff = get_object_or_404(Item, id=self.kwargs['pk']) total_likes = stuff.total_likes() context['total_likes']= total_likes return context -
Datetime in Django
I have date_ordered as DateTimeField in models.py , with auto now add = True. In admin , the time is perfect for date_ordered . But in terminal , it shows time as dateordered + 4 hrs something . I have Admin site date date in admin which is perfect. But Terminal date in terminal class Order(models.Model): date_ordered = models.DateTimeField(auto_now_add = True) I have this in settings.py LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Kathmandu' USE_I18N = True USE_L10N = True USE_TZ = True -
Access django by WAN IP instead of domain
I'm using the pydanny-cookiecutter, and during the initial prompts, I gave a domain that I no longer wish to use. How can I update to just be able to access the service by the WAN IP of the digital ocean droplet I am running in? So far I've opened ports 5000 and 5555 in the droplet and manually (ssh into postgres container) inserted a new record into django_sites with ID 2 and the domain and name both as the WAN IP. I've also updated the SITE_ID=2 in the settings base.py. I've uploaded the traefik.yml to the following, but still unable to reach the pages when I go to WANIP:5000 or WANIP:5555 log: level: INFO entryPoints: web: # http address: ":80" http: # https://docs.traefik.io/routing/entrypoints/#entrypoint redirections: entryPoint: to: web-secure web-secure: # https address: ":443" flower: address: ":5555" certificatesResolvers: letsencrypt: # https://docs.traefik.io/master/https/acme/#lets-encrypt acme: email: "<REDACTED>@gmail.com" storage: /etc/traefik/acme/acme.json # https://docs.traefik.io/master/https/acme/#httpchallenge httpChallenge: entryPoint: web http: routers: web-secure-router: rule: "HostRegexp(`<REDACTED WAN IP>`)" entryPoints: - web-secure middlewares: - csrf service: django tls: # https://docs.traefik.io/master/routing/routers/#certresolver certResolver: letsencrypt flower-secure-router: rule: "HostRegexp(`<REDACTED WAN IP>`)" entryPoints: - flower service: flower tls: # https://docs.traefik.io/master/routing/routers/#certresolver certResolver: letsencrypt middlewares: csrf: # https://docs.traefik.io/master/middlewares/headers/#hostsproxyheaders # https://docs.djangoproject.com/en/dev/ref/csrf/#ajax headers: hostsProxyHeaders: ["X-CSRFToken"] services: django: loadBalancer: servers: - url: http://django:5000 … -
RuntimeError: unable to perform operation on the handler is closed. Django and Flutter
I am new to WebSocket programming and Dart/Flutter programming, but not new to Django/Python. This toy project is my self-studying in free time I pick awesome Django boilerplate from here and follow along the channels's tutorial here Web browser Chrome be able to reproduce the example. Next I try Flutter tutorial I expect user in the mobile be able to listen to the message and send message. But my mobile can only receive the message from web user. Problem: When the mobile send the message. Django disconnect its connection and raises this error in terminal django | ERROR: closing handshake failed django | Traceback (most recent call last): django | File "/usr/local/lib/python3.9/site-packages/websockets/legacy/server.py", line 232, in handler django | await self.close() django | File "/usr/local/lib/python3.9/site-packages/websockets/legacy/protocol.py", line 779, in close django | await asyncio.shield(self.close_connection_task) django | File "/usr/local/lib/python3.9/site-packages/websockets/legacy/protocol.py", line 1309, in close_connection django | self.transport.write_eof() django | File "uvloop/handles/stream.pyx", line 696, in uvloop.loop.UVStream.write_eof django | File "uvloop/handles/handle.pyx", line 159, in uvloop.loop.UVHandle._ensure_alive django | RuntimeError: unable to perform operation on <TCPTransport closed=True reading=False 0x55ed26012b80>; the handler is closed django | ERROR 2021-09-25 11:05:01,093 server 11 140336674826048 closing handshake failed django | Traceback (most recent call last): django | File "/usr/local/lib/python3.9/site-packages/websockets/legacy/server.py", line 232, in … -
Django - Can I render multiple HTML, then serve them inside a zip file?
I have a site that takes orders of questions for schools. These orders have some questions, and these questions are outputted as HTML. When the order is complete I want the user to download these HTML inside a ZIP file, along other files (a PDF containing order details, and two other PDF that renders these question as a school exam) I can easily render the other files using WeasyPrint, but I can't find a way to render this multiple HTML. I tried using the render method and zipping the output of the command but it didn't work. Is this possible? -
Unable to redirect website on HTTPS in Django after using SSL_REDIRECT = True
I have created a website with an admin page and REST APIs, I am using the centOS server to deploy the website. I have this code in my settings.py file: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', # 'djangosecure.middleware.SecuritsyMiddleware' ] CORS_ALLOW_ALL_ORIGINS=True CORS_ORIGIN_WHITELIST = [ 'http://127.0.0.1:4200', 'http://localhost:4200', 'http://*'] SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_SSL_REDIRECT = True SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") If I remove the SSL_Redirect lines from code then the server runs properly but it runs on HTTP. I want my website to run on HTTPS, That is why I am using these settings. Due to these settings, my website doesn't run at all and the browser gives a response as the site took too long to respond. When I see logs, all the endpoints are giving 301 as a response code. I am not able to get that why this happening. I have gone through all the Django SSL Documentation but I did not find any solution. LOGS: 2021-09-25 16:24:18,091 autoreload 598 INFO Watching for file changes with StatReloader 2021-09-25 16:24:19,585 server 110 INFO HTTP/2 support enabled 2021-09-25 16:24:19,585 server 121 INFO Configuring endpoint tcp:port=8001:interface=0.0.0.0 2021-09-25 16:24:19,588 server 155 INFO Listening on TCP address 0.0.0.0:8001 … -
How to set category of every items inside the response in rest framework django?
I have two models like this: class Category(models.Model): title = models.CharField(max_length=256) class Post(models.Model): title = models.CharField(max_length=256, default=None, blank=True) content = models.TextField() created_at = models.DateTimeField(auto_now=True) category_id = models.ForeignKey(Category, on_delete=models.CASCADE) And have two serializer: class CategorySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Category fields = ['id', 'title'] class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ['id', 'title', 'content', 'created_at', 'category_id'] How to prepare response like this: "data": [ { "id": 1, "title": "Hello1", "content": "Hello content1", "created_at": "2021-09-25T07:57:23.532416Z", "category_id": 11, "category": {"id":11 , "title":"Category1"} }, { "id": 2, "title": "Hello2", "content": "Hello content2", "created_at": "2021-09-25T08:08:37.984310Z", "category_id": 12, "category": {"id":12 , "title":"Category2"} } ] -
Django how to solve apps aren't loaded yet error?
I am using apscheduler for my Django project. I am trying to list all users every 10 seconds. But when I try that there is an error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. scheduler.py from apscheduler.schedulers.background import BackgroundScheduler from accounts.models import UserProfile sched = BackgroundScheduler() def period(): users = UserProfile.objects.all() print(users) def start(): sched.add_job(period, 'interval', seconds=10) sched.start() apps.py from django.apps import AppConfig from dashboard.scheduler import start class DashboardConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'dashboard' def ready(self): start() accounts/models.py from django.contrib.auth.models import AbstractUser from django.db import models class UserProfile(AbstractUser): username = models.CharField(max_length=500, unique=True) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) password = models.CharField(max_length=250) email = models.EmailField(max_length=254) isUserActive = models.BooleanField(default=False) def __str__(self): return self.username For example, when I do: def period(): print("okey!") It is working. But when I try to get a model objects, it gives an error. How can I solve it? traceback Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\edeni\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Users\edeni\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "C:\Users\edeni\Desktop\project\myvenv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\edeni\Desktop\project\myvenv\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Users\edeni\Desktop\project\myvenv\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\edeni\Desktop\project\myvenv\lib\site-packages\django\core\management\__init__.py", line 375, in execute autoreload.check_errors(django.setup)() … -
Why unable to get related data in Self-referencing many-to-many in Django?
I and new to django and working on a small application containing a model nameCustomUser.CustomUser is having ManyToMany relationship with itself, i have implemented feature, that a user can follow another user.But when i am trying to fetch all the users which current authenticated is following i am not getting the desired result. Models:- class CustomUser(AbstractUser): email = models.EmailField(max_length=250, null=False, unique=True) name = models.CharField(max_length=50, null=False) username = models.CharField(max_length=50, null=False) password = models.CharField(max_length=15, null=False) user = models.ManyToManyField('self', through='Relationship', symmetrical=False, related_name='related_to') USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name', 'username'] def get_all_followings(self): print("print {}".format(self)) print("all followings {}".format(self.to_person)) view:- def see_all_followings(request): if request.method == 'GET': current_user = CustomUser.objects.get(id=request.user.id) all_followings = current_user.get_all_followings() # return render(request, "all_followings.html", {'users':, 'is_follow': True}) OutPut which i got:- Quit the server with CTRL-BREAK. print deep@gmail.com all followings user.Relationship.None # But user is following one user.. Thanks in advance.. Hope to here from you soon.. -
Add atribute to a Crispy Form to upload multile files
I use Crispy Forms in my Django app. I need to upload multiple files with one button, so insted of 'Choose file' I need 'Choose files'. My models: models.py file_1 = models.FileField(blank=True, upload_to='PN_files/%Y/%m/%d/', verbose_name="File 1", validators=[validate_file_size], help_text="Allowed size is 50MB") My view: views.py class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'file_1'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) HTML code: {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Fill form</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Submit</button> </div> </form> </div> {% endblock content %} How can I add something like: file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) to my 'file_1' field to upload multiple files? -
Django FileResponse: PermissionError: [WinError 32] The process cannot access the file because it is being used by another process
I have been trying to return a file using django FileResponse, but faced a problem: file instance cannot be deleted after response has been sent. Before that implementation, I have used tempfile module, but it also did not work. from rest_framework import views from django.http import FileResponse import os class DownloadShoppingCartView(views.APIView): def get(self, request): try: with open('test.txt', 'w') as file: file.write('supertest\n') return FileResponse( open(file.name, mode='rb'), as_attachment=True, status=status.HTTP_200_OK ) except Exception as e: print('There will be exception handling') finally: """I also have been trying to put here time.sleep(5), but there was no positive result. """ os.remove(file.name) Full traceback: Internal Server Error: /api/recipes/download_shopping_cart/ Traceback (most recent call last): File "C:\Users\Justm\dev\foodgram-project-react\backend\.venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Justm\dev\foodgram-project-react\backend\.venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Justm\dev\foodgram-project-react\backend\.venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\Justm\dev\foodgram-project-react\backend\.venv\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Justm\dev\foodgram-project-react\backend\.venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Users\Justm\dev\foodgram-project-react\backend\.venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\Justm\dev\foodgram-project-react\backend\.venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\Justm\dev\foodgram-project-react\backend\.venv\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\Justm\dev\foodgram-project-react\backend\recipes\views.py", line 141, in get os.remove(file.name) PermissionError: [WinError 32] The process cannot access the file because it is being … -
How to insert image using Django BinaryField and Postgresql Bytea with Django Rest Framework?
I want to insert image to database. I use Django Rest Framework and Django BinaryField in model and use Postgresql Bytea data type. This is my code : models.py class Question(models.Model): question_id = models.BigAutoField(primary_key=True) question = models.TextField(default=None, null=True) question_picture = models.BinaryField(default=None, null=True) answer = models.CharField(max_length=255) mc_a = models.CharField(max_length=255) mc_b = models.CharField(max_length=255) mc_c = models.CharField(max_length=255) class Meta: managed = True db_table = 'question' def __str__(self): return self.question serializers.py class QuestionSerializer(serializers.ModelSerializer): class Meta: model = Question fields = ('question_id', 'question', 'question_picture', 'answer', 'mc_a', 'mc_b', 'mc_c') views.py @api_view(['POST']) def question_list(request): if request.method == 'POST': question_data = JSONParser().parse(request) questions_serializer = QuestionSerializer(data=question_data) if questions_serializer.is_valid(): questions_serializer.save() return JsonResponse(questions_serializer.data, status=status.HTTP_201_CREATED) return JsonResponse(questions_serializer.errors, status=status.HTTP_400_BAD_REQUEST) With the above code that I tried to run to insert data. When I checked the database, the question_picture data (image) was empty, but the other data was filled. How do I insert the image so that it can be stored in the database? -
How to revert back data entry if first query fails
Heres my code: data = { "order_type":"order", "user_id":user_id, "order_total":order_total, ... } serialzier = UserOrderSer(data=data) if serialzier.is_valid(raise_exception=True): serialzier.save() product_data = [] for i in all_response: div = mysplit(i['pack']) product_unit = div[0] product_unit_value = div[1] product_data.append({ "order_id": serialzier.data['order_id'], "product_id":i['product_id'], "product_name":i['product_name'], "product_price": i['selling_price'], ... }) product_serializer = UserOrderProductSer(data=product_data,many=True) if product_serializer.is_valid(raise_exception=True): product_serializer.save() If the product_serializer.is_valid fails, then i want the serialzier = UserOrderSer(data=data) entry to revert back. Since, i'm using id of 1st entry in 2nd entry i cannot check .is_valid both at same time -
Reverse for 'filename' not found. 'filename' is not a valid view function or pattern name
i am trying to redirect from my menu item to another page with some parameter in django i am writting code like this <li><a class="dropdown-item" href="{% url 'MscItPdf_Note' '1' 'SC' %}">Soft Computing</a> for this url.py is path('MscItPdf_Note/<str:semester>/<slug:subject>/',views.MscItPdf_Note,name='MscItPdf_Note') and in views.py def MscItPdf_Note(request,semester,subject): pdfNotes_file=MscItPDF_Notes.objects.all().filter(subject=subject) n=len(pdfNotes_file) print("hello",pdfNotes_file) params={'pdfnote':pdfNotes_file,'total_items':n} return render(request,'pdfNotes.html',params) it gives error like this NoReverseMatch at /MscItPdf_Note/1/SC/ Reverse for 'filename' not found. 'filename' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/pdfNote/5/MIS/ Django Version: 3.2.7 Exception Type: NoReverseMatch Exception Value: Reverse for 'filename' not found. 'filename' is not a valid view function or pattern name. Exception Location: C:\Users\ashwi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py, line 694, in _reverse_with_prefix Python Executable: C:\Users\ashwi\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.7 where am i making wrong? and what's the solution for this? -
Django - How to pass data to new view (not in url)
How can i pass/redirect few variables to new view but i want to make it under the scene not in URL. models.py class Parings_3(models.Model): name = models.CharField(max_length=64) p1 = models.CharField(max_length=16, choices=ARMIES_CHOICE) p2 = models.CharField(max_length=16, choices=ARMIES_CHOICE) p3 = models.CharField(max_length=16, choices=ARMIES_CHOICE) op1 = models.CharField(max_length=16, choices=ARMIES_CHOICE) op2 = models.CharField(max_length=16, choices=ARMIES_CHOICE) op3 = models.CharField(max_length=16, choices=ARMIES_CHOICE) p11 = models.IntegerField() p12 = models.IntegerField() p13 = models.IntegerField() p21 = models.IntegerField() p22 = models.IntegerField() p23 = models.IntegerField() p31 = models.IntegerField() p32 = models.IntegerField() p33 = models.IntegerField() date = models.DateField(auto_now_add=True) forms.py class ParingsForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ParingsForm, self).__init__(*args, **kwargs) for i in ["p11", "p12", "p13", "p21", "p22", "p23", "p31", "p32", "p33"]: self.fields[i].widget.attrs["min"] = -2 self.fields[i].widget.attrs["max"] = 2 class Meta(): model = Parings_3 fields = ["name", "p1", "p2", "p3", "op1", "op2", "op3", "p11", "p12", "p13", "p21", "p22", "p23", "p31", "p32", "p33"] views.py class AddParing3View(View): def get(self, request): form = ParingsForm() ctx = {"form": form} return render(request, "add_paring_3_form.html", ctx) def post(self, request): form = ParingsForm(request.POST) if form.is_valid(): form.save() return redirect("parings-view") class ParingDetails3View(View): def get(self, request, id): player = Parings_3.objects.get(pk=id) teamA = [player.p1, player.p2, player.p3] teamB = [player.op1, player.op2, player.op3] ctx = { "teamA": teamA, "teamB": teamB, "player": player } return render(request, "paring_details_3.html", ctx) views.py with sessions class AddParing3View(View): def get(self, … -
Why does my "id" field disappear in my serializer (manytomany)?
I have a "PriceTable" object that can contain several "PriceLine" objects with a manytomany relationship. I use django rest framework to publish an api and I would like that when I use PUT or PATCH on PriceTable, I can also modify the content of PriceLine. The goal is to have a unique UPDATE method to be able to modify the instances of the 2 objects. My models: class PriceTable(models.Model): name = models.CharField(_('Name'), max_length=255) client = models.ForeignKey( "client.Client", verbose_name=_('client'), related_name="price_table_client", on_delete=models.CASCADE ) lines = models.ManyToManyField( 'price.PriceLine', verbose_name=_('lines'), related_name="price_table_lines", blank=True, ) standard = models.BooleanField(_('Standard'), default=False) class Meta: verbose_name = _("price table") verbose_name_plural = _("price tables") def __str__(self): return self.name class PriceLine(models.Model): price = models.FloatField(_('Price')) product = models.ForeignKey( "client.Product", verbose_name=_('product'), related_name="price_line_product", on_delete=models.CASCADE, ) class Meta: verbose_name = _("price line") verbose_name_plural = _("price line") def __str__(self): return f"{self.product.name} : {self.price} €" I want to be able to send a JSON of this format to modify both the table and its lines: { "id": 16, "lines": [ { "id": 1, "price": 20.0, "product": 1 }, { "id": 2, "price": 45.0, "product": 2 } ], "name": "test" } For this, I try to override the update method of my serializer: class PriceTableSerializer(serializers.ModelSerializer): """ PriceTableSerializer """ lines … -
Django m2m_changed post_clear get cleared objects
In Django docs about m2m_changed signal, it's said that pk_set argument to the signal handler is None for clear actions: pk_set ... For the pre_clear and post_clear actions, this is None. But on post_clear action, how can one know what relations are removed? (On pre_clear it can be achieved by simply querying the relation, since it's not cleared yet.) -
MakeMigration Error on Django - ImportError: cannot import name 'UserProfile'
I want to create a back-end server for an online video website with Django. There are user information and video information in the database. I want users to pay attention to each other and collect videos. Users can also upload videos. For this I registered two apps: user and video. And added to INSTALLED_APPS. After I writing models.py, I run python manage.py makemigrations and reported error: File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "D:\Code\PycharmProjects\djangoProject_dachuang\venv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "D:\Code\PycharmProjects\djangoProject_dachuang\venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute django.setup() File "D:\Code\PycharmProjects\djangoProject_dachuang\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\Code\PycharmProjects\djangoProject_dachuang\venv\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "D:\Code\PycharmProjects\djangoProject_dachuang\venv\lib\site-packages\django\apps\config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "D:\Program Files\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "D:\Code\PycharmProjects\djangoProject_dachuang\user\models.py", line 8, in <module> from video.models import Video File "D:\Code\PycharmProjects\djangoProject_dachuang\video\models.py", line 20, in <module> from user.models import UserProfile ImportError: cannot import name 'UserProfile' this is user->models.py: from django.db … -
Trying to create an advertisement-like system to distribute ads to my website and further monetize it using Django
I have created a Django App which takes Image and Video Advertisements to the database and then renders it to a template where we can view every Ads and perform CRUD operations. Every Unique User may create or delete his own Ads. He will not be able to perform any operation on Other User's Ads. However, I want these Ads get circulated over my website (at first randomly, later we can distribute along the weight and type-investment of the advertisements) and circulate as it may be any type of advertisements from any Advertisement Company. Also, How will I distribute it into my website so that in every frame or container right advertisements appear. Secondly, I also want to know how can I help monetize my website and also how can i monetize advertisements and the idea of earning through advertisements. I am using Python and Django Framework and studying different packages to learn it. Please give me some tips and working of how to achieve this. Thank you for your time . -
ImageField Overwrite with different file name in Django
HI i am making a project in django where upload image and render is there but i want to make the project like it replace the previous image which can be in different name Like if i upload a image first like san.png and second time if i upload sanju.png the previous one should delete automatically and in folder there should be only one image..... How can i make the logic?? MODELS.PY from django.db import models class Image(models.Model): image = models.FileField(upload_to='images', max_length=255) -
django.db.utils.OperationalError: no such column: ...?
I got the fowling error when i ran ./manage.py migrate in django sqlite DB django.db.utils.OperationalError: no such column: users_user.phone_number then when I deleted all migrations history and makemigrations it solved. But of course I back the to prevues commit because I don’t want to delete the migrations history. Any idea to solve that without deleting the migrations history? full error messsage File "/Users/apple/.local/share/virtualenvs/backend-_hch_eH3/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/Users/apple/.local/share/virtualenvs/backend-_hch_eH3/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 383, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such column: users_user.phone_number The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pycharm/django_manage.py", line 52, in <module> run_command() File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pycharm/django_manage.py", line 46, in run_command run_module(manage_file, None, '__main__', True) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 205, in run_module return _run_module_code(code, init_globals, run_name, mod_spec) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 96, in _run_module_code mod_name, mod_spec, pkg_name, script_name) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/runpy.py", line 85, in _run_code exec(code, run_globals) File "/Users/apple/Documents/GitHub/solitary-poetry-26574/backend/manage.py", line 21, in <module> main() File "/Users/apple/Documents/GitHub/solitary-poetry-26574/backend/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Users/apple/.local/share/virtualenvs/backend-_hch_eH3/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() -
Django regex on template?
I need to make menu active based when user visits a page ! And it should also work on sub pages, how to allow everything after a particular word ? {% with request.resolver_match.url_name as url_name %} <li class="menu-item {% if url_name in 'settings, settings-password' %}active{% endif %}"> <a href="{% url 'settings' %}" class="nk-menu-link"> <span class="menu-text">Settings</span> </a> </li> {% endwith %} In the above, am adding these settings, settings-password, how to allow everything after settings to make the menu active ? I have other pages who has many sub pages, so its not fare to add everything under if In loop, so if i can allow everything after a word, for ex: How to make menu active which contains "settings" in their view name ? Please suggest -
Not able to load template that has been extended in Django
The django 'extends' template is not loading the content. In this I am trying to extend index.html to homepage.html. Both the files are under the same templates directory. The code snippets are shown below: index.html <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <title> Tashi eComm</title> <!-- adding title icon --> <link rel = "icon" href ="{% static 'images/TecommLogo.png' %}" type = "image/x-icon"> <!-- Bootstrap 5 link --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous"> <!-- Bootstrap 5 popper and javascript link --> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.3/dist/umd/popper.min.js" integrity="sha384-W8fXfP3gkOKtndU4JGtKDvXbO53Wy8SZCQHczT5FMiiqmQfUpWbYdTil/SxwZgAN" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.min.js" integrity="sha384-skAcpIdS7UcVUC05LJ9Dxay8AXcDYfBJqt1CJ85S/CFujBsIzCIv+l9liuYLaMQ/" crossorigin="anonymous"></script> <!--Bootstrap icons--> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.5.0/font/bootstrap-icons.css"> <!-- stylesheet --> <link rel="stylesheet" type="text/css" href="{% static 'css/stylesheet.css' %}"/> </head> <body> <div class="wrapper"> <div class="panel panel-default"> <div class="panel-heading"> <div class="d-flex justify-content-end "> <div class="top-header m-2 "> <a href="#">Marketplace</a> </div> <div class="top-header m-2 ">|</div> <div class="top-header m-2"> <a href="#">Buyer Protection</a> </div> <div class="top-header m-2 ">|</div> <div class="top-header m-2"> <a href="#">Track Order</a> </div> <div class="top-header m-2 ">|</div> <div class="top-header m-2"> <div class="form-group"> <select id="demo_overview_minimal" class="select-picker" data-role="select-dropdown" data-profile="minimal"> <!-- options --> <option>BTN</option> <option>USD</option> <option>EUR</option> </select> </div> </div> </div> </div> <div class="panel-body"> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container-fluid"> <a class="navbar-brand ms-5" href="#"><img src="{% static 'images/TecommLogo.png' %}" alt="Logo" height="60px" width="60px"></a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" … -
How to iterate over a Form in Html, store the data in a variable in Json, send it back to Django Backend
I need to iterate over an Html Form and get the data as JSON obj and send it to the Django backend to get data as objects. all(). Is this possible? In this form I am iterating over a student detail list that I have rendered to the template using Django. my form <form method="POST " id="studentform"> {% csrf_token %} <table class="table table-striped"> <thead> <tr> <th scope="col">Admission No</th> <th scope="col">First Name</th> <th scope="col">Last Name</th> <th scope="col">Present Status</th> </tr> </thead> <tbody> {% for student in student_names %} <tr> <th scope="row"> <div class="form-group "> <select class="form-control st" style="appearance: none;" id="admission_number" name="admission_number"> <option>{{student.admission_number}}</option> </select> </div> </th> <td> <div class="form-group"> <select class="form-control st" style="appearance: none;" id="first_name" name="first_name"> <option>{{student.first_name}}</option> </select> </div> </td> <td> <div class="form-group"> <select class="form-control st" style="appearance: none;" id="last_name" name="last_name"> <option>{{student.last_name}}</option> </select> </div> </td> <td> <div class="form-group"> <select class="form-control st " style="text-align: center;" id="attendance" name="attendance"> <option>Yes</option> <option>No</option> </select> </div> </td> </tr> {% endfor %} </tbody> </table> </div> </div> <div class="row"> <div class="form-group col-md-4"> <label for="birthdaytime">Grade :</label> <select class="form-control" style="appearance: none; font-size: 18px; font-weight: 500;" id="grade" name="grade"> <option>{{user.studying_grade}}</option> </select> </div> <div class="form-group col-md-4"> <label for="birthdaytime">Subject :</label> <select class="form-control" style="appearance: none; font-size: 18px; font-weight: 500;" id="subject" name="subject"> <option>{{user.assigned_subject}}</option> </select> </div> <div class="form-group col-md-4"> </div> <button … -
Django render django-tag from html
Does anyone know if you can have a django tag, like {{ val }} render another tag within it? Something like: {{ val }} where val="{% static 'path/to/file' %}" and have that render the static file? The reason why i am asking is because i am trying to write easy pages with markdown and have a django app template render them for me with {{ val | markdown | safe }} now everything was fine locally because i was using relative paths for image links, however in production these all broke because they were not using {% static %}. So my goal is to try to swap the markdown links with the proper django static tags but i realize that django does not render a nested tag (or at least i was not able to find a way for it to do it). I am open to suggestions if there is an alternative better way as well since i've been at this for a few days! Thanks for the help in advance.