Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django causes error when I'm trying to send email. Error message: [Errno 61] Connection refused
I'm trying to send email from Django. My Django settings configurations are as follows: # SMTP Settings EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_HOST_USER = "my_email@gmail.com" # my email address goes here. EMAIL_HOST_PASSWORD = "my_generated_password" # generated password EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = "fmk@gmail.com" However when I'm trying to send email from it either using celery or directly from views it says "[Errno 61] Connection refused". N.B: I'm using a mac matchine for the development. Is there any security reason for send email using Mac. Views Code Sample: def send_mail_to_all(request): send_mail('Celery Test Mail Subject', "Test Mail Body", from_email='sender@gmail.com', recipient_list=['repientsemail@gmail.com'], fail_silently=False ) # send_mail_func.delay() return HttpResponse('Sent') Celery Task Schedular Code: @shared_task(bind=True) def send_mail_func(self): users = get_user_model().objects.all() for user in users: mail_subject = "Celery Testing" message = f"This is the celery testing message at {datetime.now()}" to_email = user.email send_mail(mail_subject, message, from_email=settings.EMAIL_HOST_USER, recipient_list=[to_email,], fail_silently=False ) return 'Done' -
create a dictionary of with key as the attribute and value as model object
Say i have this table: class Blog(models.Model) title = models.CharField() body = models.CharField() author = models.ForeignKey(Author) I need to create 3 rows with the title (title_1, title_2, title_3). I need to fetch all the blog objects and create a dictionary with key as the title and value as blog object. blog_dict = {'title_1': <blog_object_1>, 'title_2': <blog_object_2>, 'title_2': <blog_object_3>} I have 1 million records to work. Is there any efficient way to do it? -
Django Python urlencode same key with multiple values
As the title suggest I am trying to urlencode using Ordered Dict in python def url_replace(request, field, value, direction=""): dict_ = request.GET.copy() if field == "order_by" and field in dict_.keys(): if dict_[field].startswith("-") and dict_[field].lstrip("-") == value: dict_[field] = value elif dict_[field].lstrip("-") == value: dict_[field] = "-" + value else: dict_[field] = direction + value else: dict_[field] = direction + str(value) print("UNORDERED___________________") print(dict_) print(super(MultiValueDict, dict_).items()) print("ORDERED_____________") print(OrderedDict(super(MultiValueDict, dict_).items())) print(OrderedDict(dict_.items())) return urlencode(OrderedDict(dict_.items())) The output for the above code UNORDERED___________________ <QueryDict: {'assigned_to_id': ['1', '2'], 'client_id': ['2', '1'], 'page': ['2']}> dict_items([('assigned_to_id', ['1', '2']), ('client_id', ['2', '1']), ('page', ['2'])]) OrderedDict([('assigned_to_id', '2'), ('client_id', '1'), ('page', '2')]) ORDERED_____________ OrderedDict([('assigned_to_id', ['1', '2']), ('client_id', ['2', '1']), ('page', ['2'])]) OrderedDict([('assigned_to_id', '2'), ('client_id', '1'), ('page', '2')]) As you can see the assigned_to_id has only 2 in the end . What I am expecting is a ordered dict with OrderedDict([('assigned_to_id', '2'),('assigned_to_id', '1'), ('client_id', '1'), ('client_id', '2'),('page', '2')]) Maybe there might be a better approach for this, I am a bit new to python My final aim is to return a dict with multiple keys or anything that can be used in urlencode -
Display Model Hierarchy of a field in django admin form
I have django models like below: class Subscription(models.Model): """ A subscription to a product. """ # Possible interval values. user = models.ForeignKey( to='account.User', related_name='subscriptions', on_delete=models.PROTECT, ) uuid = models.UUIDField(unique=True, default=uuid4) product = models.ForeignKey( to='product.Product', related_name='subscriptions', blank=True, null=True, on_delete=models.PROTECT, ) base_plan = models.ForeignKey( to='product.Plan', on_delete=models.PROTECT, ) #code goes on... class Plan(models.Model): """ Specifies a given set of billing parameters for a package. """ name = models.CharField(_('name'), max_length=50) uuid = models.UUIDField(unique=True, default=uuid.uuid4) product = models.ForeignKey(to=Product, related_name='plans', on_delete=models.PROTECT) package = models.ForeignKey(to=Package, related_name='plans', on_delete=models.PROTECT) #code goes on... class Product(BillingProduct): """ A product is a collection of features that can be subscribed to. """ name = models.CharField(_('name'), max_length=50) uuid = models.UUIDField(unique=True, default=uuid.uuid4) slug = models.SlugField(_('slug')) active = models.BooleanField(_('active'), default=True) description = models.TextField(help_text=_("The public-facing description for the product can include HTML."), blank=True) #code goes on... class Package(models.Model): """ Specifies a collection of features that a user can buy or trial. """ name = models.CharField(_('name'), max_length=50) uuid = models.UUIDField(_('UUID'), unique=True, default=uuid.uuid4) product = models.ForeignKey(to=Product, related_name='packages', help_text=_("Must match features selected."), on_delete=models.PROTECT) feature_set = models.OneToOneField(to='product.FeatureSet', related_name='+', on_delete=models.PROTECT) #code goes on... and Django Form like below that will be used in SubscriptionAdmin: class SubscriptionForm(forms.ModelForm): class Meta: model = Subscription exclude = [] widgets = { 'user': CustomerWidget } base_plan = … -
I have some issues I never had to deal with in the development phase. When the users posts some actions, I sometimes get the following error
What really frustrates me is that the project works fine in the local environment and furthermore, the matching query object DOES NOT exist in the Database. And also my password1 and password2 fields does not exits in database table even i created in form.py. Image of error page -
none is saving in django admin
productscreate.html <form data-bind="submit: save" method="post"> {% csrf_token %} <table border="1"> <tr> <td>Title: <input type="text" name="title" id="title" data-bind="value: $data.title"></td> <br> </tr> <tr> <td>Description: <textarea name="description" id="description" data-bind="value: $data.description">Description</textarea></td> <br> </tr> <tr> <td>Image: <input type="file" name="image" id="image" ></td> <br> </tr> <tr> <td><button type="button" id="submit" data-bind="click: save">Submit</button></td> </tr> </table> </form> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.0/knockout-min.js"></script> <script> function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); </script> <script> var ViewModel = function () { var self = this; self.title = ko.observable(""); self.description = ko.observable(""); var FormData = { title: self.title, description: self.description, }; console.log(FormData); self.save = function () { $.ajax({ type: "POST", url: 'http://127.0.0.1:8000/productsadd', data: FormData, contentType: "application/json", headers: {'X-CSRFToken': csrftoken}, cache: false, enctype: "multipart/form-data", //processData: false, success: function (FormData) { alert("successfull") window.location = '{% url "productslist" %}'; }, error: function () { alert("fail"); } }); }; }; ko.applyBindings(new ViewModel()) </script> views.py class ProductsCreate(CreateView): model … -
Django application run without command line like php web application
I want to launch Django application without giving command "python manage.py runserver". Like how php works, when hit the index file it will launch the application but in django/python i didn't find any way to do that in windows OS except run the project from command line which is cautious for robust application. Please let me know/suggest any idea about if it is possible for windows or not?? -
Issue to call message handler (Django Channels)
I have this portion of code in my app/views.py (to send signals to the group over the websocket just priori posting a new object in my db): from django.core import serializers import channels.layers from .consumers import serialize_games from asgiref.sync import async_to_sync def send_game_update(event): ''' Call back function to send message to the browser ''' print('@call_back:into it') message = event['message'] channel_layer = channels.layers.get_channel_layer() # Send message to WebSocket async_to_sync(channel_layer.send)(text_data=json.dumps( message )) print('@call_back: messages sent to lobby') def send_update_signal(): games = serialize_games() channel_layer = channels.layers.get_channel_layer() # Send new game info to Lobby async_to_sync(channel_layer.group_send)( 'Lobby', { 'type': 'send_game_update', 'message': games }) print('@receiver: just before messages sent to lobby') And django raises: ValueError: No handler for message type send_game_update Exception inside application: No handler for message type send_game_update Is that a namespace issue? -
How to link comment model to Post model django
I want to link a comment model to post when multiple posts are displayed in a page i want to access the post id of the post i am commenting on but i do not know how please tell me how to link the comment model I am a begginner here so i apologize for any errors Please comment if any more of code is needed template : {% for Img in imgs %} <div class="container"> <div class="card"> <div class="card-image waves-effect waves-block waves-light"> <img class="activator" src="{{ Img.Post_Img.url }}" alt="image"> </div> <div class="card-content"> <img src="{{ Img.op.userprofile.Profile_pic.url }}" class="profiles" alt="{{ Img.op.userprofile.Nick_Name }}"> <span class="OP">{{ Img.op.userprofile.Nick_Name }}</span> <span class="card-title activator white-text text">{{ Img.Title }}<i class="material-icons right">more_vert</i></span> <p><a href="https://www.youtube.com/watch?v=dQw4w9WgXcQ">Vote</a></p> </div> <div class="card-reveal darken-4 black"> <span class="card-title white-text text">{{ Img.Title }}<i class="material-icons right">close</i></span> <form method="post"> {% csrf_token %} {{ comment }} <button class="btn waves-effect waves-light" type="submit" name="action">Submit <i class="material-icons right">send</i> </button> </form> {% for comment in comments %} {{ comment.op.userprofile.Nick_Name }}{{ comment.comment }} {% endfor %} </div> </div> </div> {% endfor %} models : class MemeImg(models.Model): Title = models.CharField(max_length=500) date_created = models.DateTimeField(auto_now_add=True) op = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1) Post_Img = CloudinaryField('Post') def __str__(self): return self.Title class Comments(models.Model): post = models.ForeignKey(MemeImg, on_delete=models.CASCADE) op = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1) … -
Install django on windows with a Virtualenv
I'm at the end of my rope here. I have been trying for two days to get django deployed on a windows machine (as in full deployment). I can get python and django, postgres everything in place and the django test server works. Then all goes to pot!! I have tried configuring IIS, and tried Nginx/Waitress and had issues with both. On the last one django manage.py just stopped working. Does anybody know of a guide that actually works on prod deployment on windows. without having to guess at missing pieces and the need to reinstall windows half a dozen times. I would also like to deploy in a virtualenv as I and using cython compiled files so need to use a specific python version Thanks Pigged off Linux User!!! -
Django: Why does my custom command starts the server?
I am trying to use Scrapy with Django so I defined the following custom management command: from django.core.management.base import BaseCommand from scraper.spiders.sparerooms import SpareroomsSpider from scrapy.crawler import CrawlerProcess from scrapy.utils.project import get_project_settings from scrapy.settings import Settings import os class Command(BaseCommand): help = "Release the spiders" def handle(self, *args, **options): os.environ.setdefault('SCRAPY_SETTINGS_MODULE', 'scraper.settings') process = CrawlerProcess(get_project_settings()) process.crawl(SpareroomsSpider) process.start() When I run the command python3 manager.py crawl the server is instantiated; I can see libraries and files from another app being loaded before crawling, which is really annoying as I have a large amount of data to load (30min wait). It wouldn't be such a problem if the server was usable. However, request.META is not set (unable to use request.build_absolute_uri()) and the endpoints are not reachable Error 111: Connection Refused. All of this works fine if I start the server with python3 manage.py runserver and than use the custom command (which loads the server again). What am I doing wrong? Can it be fixed? -
Unable to create API from django rest_framework
Can anyone please help me? I am not able to create API with GET POST PUT DELETE methods. Also when I go to this url: "http://127.0.0.1:8000/api/packages/" I cant see Django default API view. My users API is working fine with all methods but not packages. Models.py class Customer(models.Model): user = models.OneToOneField( User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=50, null=True) phone = models.CharField(max_length= 200, null = True) dob = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Packages(models.Model): STATUS = ( ('Drafts', 'Drafts'), ('Published', 'Published'), ) name = models.CharField(max_length=50, null=True) details = models.CharField(max_length=200, null=True) price = models.PositiveIntegerField() days = models.CharField(max_length=10, null=True) nights = models.CharField(max_length=10, null=True) image = models.ImageField(null=True, blank=True) status = models.CharField(max_length=200, null=True, choices=STATUS) def __str__(self): return self.name Views.py @csrf_exempt def packagesAPI(request, id=0): if request.method == 'GET': packages = Packages.objects.all() packages_serializer = PackagesSerializer(packages, many=True) return JsonResponse(packages_serializer.data,safe=False) elif request.method == 'POST': packages_data = JSONParser().parse(request) packages_serializer = PackagesSerializer(data = packages_data) if packages_serializer.is_valid(): packages_serializer.save() return JsonResponse("Added Successfully",safe=False) return JsonResponse("Failed to Add",safe=False) elif request.method == 'PUT': packages_data = JSONParser().parse(request) packages = Packages.objects.get(package_id = packages_data['package_id']) packages_serializer = PackagesSerializer(packages,data = packages_data) if packages_serializer.is_valid(): packages_serializer.save() return JsonResponse("Updated Successfully",safe=False) return JsonResponse("Failed to Update") elif request.method == 'DELETE': packages = Packages.objects.get(package_id=id) packages.delete() return JsonResponse("Deleted Successfully",safe=False) @csrf_exempt def SaveFile(request): file = requestFILES['file'] file_name … -
Trying to connect Docker + Django to Postgres - could not translate host name "db" to address: Name or service not know
I'm trying to Dockerize a Django + Postgres project following this tutorial: https://docs.docker.com/samples/django/ When I run docker-compose up I get: django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known Dockerfile # syntax=docker/dockerfile:1 FROM python:3 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ docker-compose.yml version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres depends_on: - db settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': config('DB_NAME'), 'USER': config('DB_USER'), 'PASSWORD': config('DB_PASSWORD'), 'HOST': config('DB_HOST'), 'PORT': 5432, } } -
Need to add a search functionality on Django class based view
I have a search function on a function based view that works fine. This is the function based view code: def BlogList(request): blogs = Blog.objects.all() if request.method == 'GET': search = request.GET.get('search', '') blogs = Blog.objects.filter(blog_title__icontains=search) return render(request, 'App_Blog/blog_list.html', context={'search':search, 'blogs':blogs}) But now I want to replace that function based view by implementing it on this class based view. class BlogList(ListView): context_object_name = 'blogs' model = Blog template_name = 'App_Blog/blog_list.html' This is my models.py: class Blog(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='post_author') blog_title = models.CharField(max_length=264, verbose_name="Put a Title") slug = models.SlugField(max_length=264, unique=True) blog_content = models.TextField(verbose_name="What is on your mind?") blog_image = models.ImageField(upload_to='blog_images', verbose_name="Image") publish_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) class Meta: ordering = ['-publish_date',] def __str__(self): return self.blog_title html part for search function: <form class="form-inline ml-auto" method="GET"> <input class="form-control mr-sm-2" type="text" name="search" placeholder="Search the topic"> <button class="btn btn-success" type="submit">Search</button> </form> As I am a newbie, I have tried different solutions but not getting it through. I'll be glad if someone help me on this. -
How to return raw sql queries as json objects?(Django)
I am using the following function to display the sql join query as json: def toggle_query(request,id): obj = DibbsSpiderDibbsMatchedProductFieldsDuplicate.objects.raw('''SELECT * FROM dibbs_spider_solicitation JOIN dibbs_spider_dibbs_matched_product_fields_duplicate ON dibbs_spider_solicitation.nsn = {nsn};'''.format(nsn=id)) context = serializers.serialize('json',obj) return JsonResponse(context,safe=False) This displays data as : "[{\"model\": \"dibbs_spider.dibbsspiderdibbsmatchedproductfieldsduplicate\", \"pk\": 39, \"fields\": {\"nsn\": \"1650011162908\", \"nsn2\": \"6550015746831\", \"cage\": \"34807\", \"part_number\": \"6903A-J\", \"company_name\": null, \"supplier\": \"GraingerOM\", \"cost\": \"18.16\", \"list_price\": \"19.12\", \"gsa_price\": null, \"hash\": \"665\", \"nomenclature\": \"HOUSING, CONTROL MOD\", \"technical_documents\": \"Tech Docs\", \"solicitation\": \"SPE2DS22T1575\", \"status\": \"Awarded \", \"purchase_request\": \"0091648844\\nQty: 5\", \"issued\": \"2021-12-09\", \"return_by\": \"2021-12-14\", \"file\": \"https://dibbs2.bsm.dla.mil/Downloads/RFQ/5/SPE2DS22T1575.PDF\", \"vendor_part_number\": \"269P71\", \"manufacturer_name\": \"LAMOTTE\", \"product_name\": \"Reagent Tablet Type 0 to 4 ppm Range\", \"unit\": \"EA\"}}, {\"model\": How to remove the \ symbol which is not the part of the data here ? -
Python Billiard cannot find project module on restarting Celery worker process
Running Python 2.7, Celery 3.1.23, Billiard 3.3.0.23. I'm getting the Celery workers crashing on any stack trace. Inspecting the workers using celery worker from the shell gives this stack: [2022-01-03 03:39:17,822: ERROR/MainProcess] Unrecoverable error: ImportError('No module named <my project>',) Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/celery/worker/__init__.py", line 206, in start self.blueprint.start(self) File "/usr/local/lib/python2.7/site-packages/celery/bootsteps.py", line 123, in start step.start(parent) File "/usr/local/lib/python2.7/site-packages/celery/bootsteps.py", line 374, in start return self.obj.start() File "/usr/local/lib/python2.7/site-packages/celery/concurrency/base.py", line 131, in start self.on_start() File "/usr/local/lib/python2.7/site-packages/celery/concurrency/prefork.py", line 119, in on_start **self.options) File "/usr/local/lib/python2.7/site-packages/celery/concurrency/asynpool.py", line 401, in __init__ super(AsynPool, self).__init__(processes, *args, **kwargs) File "/usr/local/lib/python2.7/site-packages/billiard/pool.py", line 972, in __init__ self._create_worker_process(i) File "/usr/local/lib/python2.7/site-packages/celery/concurrency/asynpool.py", line 415, in _create_worker_process return super(AsynPool, self)._create_worker_process(i) File "/usr/local/lib/python2.7/site-packages/billiard/pool.py", line 1068, in _create_worker_process w.start() File "/usr/local/lib/python2.7/site-packages/billiard/process.py", line 137, in start self._popen = Popen(self) File "/usr/local/lib/python2.7/site-packages/billiard/forking.py", line 91, in __init__ _Django_old_layout_hack__save() File "/usr/local/lib/python2.7/site-packages/billiard/forking.py", line 379, in _Django_old_layout_hack__save project = __import__(project_name) ImportError: No module named <my_project> It looks like Billiard is unable to load in the project module at all. However, you can run a shell on the celery worker by calling celery shell, and running forking._Django_old_layout_hack__save() works just fine. -
A Difficult Object Query
So, I have an e-commerce website that I am building. When the customer clicks "place order", the site creates the order, and the database updates totally fine. The problem lies in displaying the order summary. IF the customer has ordered from the company in the past, that order is stored in the database along with the new one. The site then throws the error "2 objects returned" when I try to access it through the foreign key that relates the order table to the User table. The reason for this is obvious to me so I added a datetime field and set the auto_now_add attribute to TRUE. The problem I'm having is selecting the latest order for that particular customer. Is there a way to use something like this? user = request.user Order.objects.filter(Customer=user).date_placed.latest() The fact that filter() returns a set makes me think that sytax won't execute properly. Maybe with a for loop inside a function that takes User as a parameter? I have no idea how to approach this one and thought I'd reach out. Thanks you guys. View for the request: def orderSummary(request): context = {} if request.user.is_authenticated: owner = request.user.id user = request.user cart = Cart.objects.get(cart_owner=owner) held_items … -
Struggling to display images using django
I am creating a blogging website using django framework and so I am struggling to display images on dynamic pages. Here is my code: models.py: class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name= 'blog_posts') updated_on = models.DateTimeField(auto_now=True) content = models.TextField() created_on = models.DateTimeField(auto_now=True) status = models.IntegerField(choices=Status, default=0) cover_image = models.ImageField() captioned_image = models.ImageField() caption = models.CharField(max_length=300) class Meta: ordering = ['-created_on'] def __str__(self): return self.title views.py: def post(request, slug): post = Post.objects.get(slug = slug) context = {'post': post} return render(request, template_name='blogger/pages.html', context=context) within my html: <img class="img-fluid" src="{{post.cover_image.url}}" /> I am unsure what I am doing incorrect here as text is correctly displaying in my code dynamically, just unable to work with images. -
Django how to write single object query in my exportcsv function?
I write this function for export csv file. I am using this query patient = Patient.objects.all() for export all objects. But I have details page for each objects and I want to export each items individually from my details page. how to write query for get single object? here is my code: models.py class Patient(models.Model): patient_name = models.CharField(max_length=150) patient_id = models.CharField(max_length=100,blank=True,null=True) date_of_birth = models.DateField() age = models.CharField(max_length=100,blank=True,null=True) phone = models.CharField(max_length=100) email = models.EmailField(blank=True,null=True) slug = models.SlugField(max_length=255,unique=True,blank=True,null=True) views.py def exportcsv(request): #I am exporting csv file from this view response = HttpResponse(content_type='text/csv') response ['Content-Disposition'] = 'attachment; filename=PatientData'+str(datetime.datetime.now())+'.csv' writer = csv.writer(response) writer.writerow(['patient_name']) patient = Patient.objects.all() for i in patient: print(i.patient_name) writer.writerow([i.patient_name]) return response #this view for showing details info of each items class PatientDeleteView(DeleteView): model = Patient template_name = 'hospital/patient-delete.html' def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) messages.add_message(self.request, messages.INFO, 'Patient Deleted Sucessfully') return data success_url = reverse_lazy('hospital:all-patient') #urls.py path('export-csv-patient-data/',views.exportcsv,name='export-csv-patient-data'), path('<slug:slug>/patient-details/',PatientDetails.as_view(),name='patient-details'), Now it's downloading all objects I want it will download only single objects from details page. -
How to get current account id in django models.py
I want to get the id of the current account in django models.py. I know I can get the user object of the current account by adding 'request.user'. However, the function I am using requires the use of the self argument to be used in the condition, so 'request' cannot be used together. Please help. [models.py] class Leave(models.Model): name = models.CharField(max_length=50, blank=True, null=True) kind = models.CharField(choices=KIND_CHOICES, max_length=20, blank=True, null=True) from_date = models.DateField(blank=True, null=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True) @property def get_html_url(self): url = reverse('leave:leave_edit', args=(self.id,)) if self.kind == 'Annual' and self.user.id == self.user_id: return f'<div class="Annual-title"><a href="{url}" style="color:black;"> {self.name} </a></div>' elif self.kind == 'Annual' and self.user.id != self.user_id: return f'<div class="Annual-title" data-toggle="modal" data-target="#leave_{self.id}"> {self.name} </div>' Does the method below work normally? [models.py] class Leave(models.Model): name = models.CharField(max_length=50, blank=True, null=True) kind = models.CharField(choices=KIND_CHOICES, max_length=20, blank=True, null=True) from_date = models.DateField(blank=True, null=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True) def user_id(request): +++ add return request.user @property def get_html_url(self): url = reverse('leave:leave_edit', args=(self.id,)) if self.kind == 'Annual' and self.user.id == Leave.user_id: return f'<div class="Annual-title"><a href="{url}" style="color:black;"> {self.name} </a></div>' elif self.kind == 'Annual' and self.user.id != Leave.user_id: return f'<div class="Annual-title" data-toggle="modal" data-target="#leave_{self.id}"> {self.name} </div>' -
Vue.js and drf images
I am currently trying to render images from my DRF to my vue.js template. I can see the image arrays in my console and have been successful using Postman with the get request but I can not seem to render the multiple images in my vue template. Im not sure whether I need to loop through the photos array in the lesson dictionary or link the id to the photo url? Any help on this would be really appreciated. Vue.js <template v-if="activeLesson"> <h2>{{ activeLesson.title }}</h2> {{ activeLesson.long_description }} <figure class="image is-square"> <img v-for="(photo, index) in activeLesson.photos" :src="activeLesson.photo_url" :key="index" /> </figure> <script> import axios from 'axios' export default { data() { return { course: {}, lessons: [], comments: [], activeLesson: null, errors: [], photo_url:'', comment: { name: '', content: '' }, } }, async mounted() { console.log('mounted') const slug = this.$route.params.slug await axios .get(`/api/v1/courses/${slug}/`) .then(response => { console.log(response.data) this.course = response.data.course this.lessons = response.data.lessons this.photos = response.data.photos }) document.title = this.course.title + ' | Relate' }, methods: { submitComment() { console.log('submitComment') this.errors = [] if (this.comment.name === '') { this.errors.push('The name must be filled out') } if (this.comment.content === '') { this.errors.push('The content must be filled out') } if (!this.errors.length) { … -
Is it better to create a OneToOne relation or a custom filed? [DJANGO]
I want to create a Venue model and save the location object, here's my code that actually works: class Location(models.Model): latitude = models.FloatField() longitude = models.FloatField() address = models.CharField(max_length=100, blank=True) city = models.CharField(max_length=100, blank=True) class Venue(models.Model): name = models.CharField(max_length=255) location = models.OneToOneField(Location) As you can see, if I delete Venue the corresponding location will not be deleted, because OneToOne works so. Is it better to create a custom field, let's say LocationField, with latitude, longitude... properties and put it inside Venue, or is this the right solution? -
Django - Saving multiple optional objects with a CreateView
I'm working on a real estate app where users can apply to rent a house or apartment. I'm having trouble grasping the concept of saving multiple objects and tying them together. I want the form to allow 1 to 4 people to apply for a single property. I either want 1 page where the user can select the number of applicants and the form save X number of people objects or I'm thinking of adding 2 buttons, on one to save and complete (current person), and another to save and add a new person. Additionally, I want to add all the applicants to a single application table. so I can query my database to view all the applicants on a single application. I'm not sure the best way to handle that. models class Properties(models.Model): property_num = models.IntegerField() property_road = models.CharField(max_length=200) rent = models.IntegerField(default=1000) city = models.CharField(max_length=200) state = models.CharField(choices=STATE_CHOICE, max_length=25) zip = models.IntegerField() bedrooms = models.IntegerField() bathrooms = models.FloatField(max_length=3) sq_foot = models.IntegerField() description = models.TextField(default=bedrooms) is_active = models.BooleanField(default=True) thumbnail = models.ImageField(upload_to='static/images', blank=True) slug = models.SlugField(blank=True, null=True, unique=True, allow_unicode=True) class Person(models.Model): address = models.ForeignKey(Properties, on_delete=models.CASCADE) requested_move_in_date = models.DateField(default=datetime.now) first_name = models.CharField(max_length=200) middle_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) dob = models.CharField(max_length=200) driver_license … -
why module 'polls.views' has no attribute 'results'
During the "Django" project, We found an error in the process of showing the results with the .html module. What is the solution to this error? import datetime from django.db import models from django.utils import timezone class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def wat_published_recently(self): return self.pub_date >= timezone.now() datetime.timedelta(day=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) # def __str__(self): # return self.choice_text polls/urls.py from django.urls import path from . import views urlpatterns = [ # ex: /polls/ path('', views.index, name='index'), # ex: /polls/5 path('<int:question_id>/', views.detail, name='detail'), # ex: polls/5/results/ path('<int:question_id>/results/', views.results, name='results'), # ex: /polls/5/vote/ path('<int:question_id>vote/', views.vote, name='vote'), # added the word 'specifics' path('specifics/<int:question_id>/', views.detail, name='detail'), ] polls/views.py from django.http import request from django.http.response import Http404 from .models import Question # from django.http import HttpResponse from django.template import loader # from django.shortcuts import render from django.shortcuts import get_object_or_404, render def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context) def detail(request, question_id): try: question = Question.objects.get(pk=question_id) except Question.DoesNotExist: raise Http404("Question does not exist") return render(request, 'polls/detail.html', {'question': question}) # def detail(request, question_id): # question = get_object_or_404(Question, pk=question_id) # return render(request, 'polls/detail.html', {'question': question}) # template … -
Connecting django app to postgres container
I'm having difficulty to connect my Django container app to my Postgres container. The docker compose statement for the Postgres app is as follows: version: '3' services: database: image: "postgres" # use latest official postgres version restart: unless-stopped env_file: - ./database.env # configure postgres networks: - djangonetwork ports: - "5433:5432" volumes: - database-data:/var/lib/postgresql/data/ # persist data even if container shuts down volumes: database-data: # named volumes can be managed easier using docker-compose networks: djangonetwork: driver: bridge The compose statement for the Django app is as follows: services: app: build: . container_name: app command: > bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" networks: - djangonetwork ports: - 10555:8000 environment: aws_access_key_id: ${aws_access_key_id} aws_secret_access_key: ${aws_secret_access_key} networks: djangonetwork: driver: bridge The difficulty emerges when performing the docker compose up statement. I have attempted a number of different POSTGRES_HOST values (note they are successfully retrieved from Amazon Secrets Manager). I receive the following log output: [+] Running 1/0 ⠿ Container app Created 0.0s Attaching to app app | /usr/local/lib/python3.10/site-packages/django/core/management/commands/makemigrations.py:105: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': could not translate host name "postgres" to address: Name or service not known app | …