Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how do i run a Script inside django?
enter image description here i created a folder containing the script text.py and init.py in app directory. i have already install Django-extentions, still am getting bugs C:\Users\Qasim\Desktop\translator>python manage.py runscript text No (valid) module for script 'text' found Try running with a higher verbosity level like: -v2 or -v3 C:\Users\Qasim\Desktop\translator>python manage.py runscript text -v2 Check for django.contrib.admin.scripts.text Check for django.contrib.auth.scripts.text Check for django.contrib.contenttypes.scripts.text Check for django.contrib.sessions.scripts.text Check for django.contrib.messages.scripts.text Check for django.contrib.staticfiles.scripts.text Check for news.scripts.text Check for rest_framework.scripts.text Check for django_extensions.scripts.text Check for scripts.text No (valid) module for script 'text' found -
Django allauth example [Errno 111] - Connection refused
I have the following error when login by FB in Django app which was uploaded to heroku: ConnectionRefusedError at /accounts/facebook/login/token/ [Errno 111] Connection refused Did I miss somethings? -
Forms has no attribute form
Hi guys im new to django so i tried to import forms from django and use it to make a section to send out articles and this is the code : from django import forms class SendArticleForm(forms.form): title = forms.CharField() body = forms.CharField(widget = forms.Textarea) published_at = forms.DateField() so after i tried to upload this code and run local server it gave me this error and i cant findout how this is happend. class SendArticleForm(forms.form): AttributeError: module 'django.forms' has no attribute 'form' -
I want to redirect to authenticate url after entering login credentials, but it is simply redirecting to same page that im in
a modal will be popped up after pressing login button, after entering details. I need it to be redirect to the following authenticate Django url. but it is showing the same site again <button type="button" class="btn btn-danger" data-toggle="modal" data-target="#exampleModalCenter"> login </button> <!-- Modal --> <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">Login</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <form method="post" action="{% url "authenticate" %}"> <div class="modal-body"> <input type="text" style="margin: 10px;margin-left: auto;margin-right: auto;width: 60%" name="username" class="form-control" placeholder="username"> <input type="password" style="margin: 10px;margin-left: auto;margin-right: auto;width: 60%" name="password" class="form-control" placeholder="password"> </div> <div class="modal-footer"> <input style="margin: auto" type="submit" class="btn btn-danger" name=""> </div> </form> </div> </div> </div> </form></nav> -
Django models queries
I have 3 tables person(id, email,password,type), user_location(id,location,u_id) and reviews(id,review,from_id,to_id). The user_location(u_id) is the foreignkey to person(id). The review(from_id,to_id) is also foreignkey to person(id). So how can i filter out a person with type 'a' and location 'b' and the reviews he got with the reviewers name? -
How to change message design in the real time chat
I have real time chat in the project, where i have two types of users: students and teachers. I want to change design of teacher messages. I tried to change consumers.py and tried to work with template but it didn't work. I think that we can do that, if we'll work with consumers.py. Who knows how to implement that? models.py class CustomUser(AbstractUser,mixins.GuardianUserMixin): email = models.EmailField(_('email_address'), unique=True, name='email') username = models.CharField(_('username'), unique=True, max_length=128) is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = UserManager() consumers.py class Consumer(WebsocketConsumer): def connect(self): self.room_name=self.scope['url_route']['kwargs']['room_name'] self.room_group_name='chat_%s' % self.room_name self.name = self.scope['user'].username if self.scope['user'].is_anonymous: self.send({'close':True}) else: async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) async_to_sync(self.channel_layer.group_send)( self.room_group_name, { "type":"chat_message", "message":self.name+" Joined Chat " } ) self.accept() def disconnect(self, code): async_to_sync(self.channel_layer.group_send)( self.room_group_name, { "type":"chat_message", "message":self.name+" Left Chat" } ) async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) def receive(self, text_data=None, bytes_data=None): text_data_json=json.loads(text_data) message=text_data_json['message'] async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type':'chat_message', 'message':self.name+" : "+message } ) def chat_message(self,event): message=event['message'] self.send(text_data=json.dumps({ 'message':message })) template <div class="ui form"> <div style="height:400px;width:100%;overflow-y:scroll" id="div_data"></div> <input type="text" name="message" id="message" placeholder="Message" style="padding:10px;width:100%; border-radius: 0px;"> <script> var roomName='{{ room_name }}'; var personname='{{ request.user.username }}'; var chatSocket=new WebSocket('ws://'+window.location.host+'/ws/chat/'+roomName+'/'); {% if request.user.is_anonymous %} window.location.pathname = '{% url 'users:login' %}' {% endif … -
Updating duplicate student Information in django
I have a bunch of CSV files that I have made to upload to a django model. 1. Created a view to upload the csv 2. Separated the fields and added them to a variable 3. Called the update_or_create() method to add the information into the model. The problem that I am facing is getting django to update the old row instead of creating a new one. If a student has failed in the first year but passes the next year, the old marks have to be updated. I am trying to filter() with the Register Number of the student and Class to narrow it down. IF there is a student with for instance AAAAAA1111 from BA 1 SEM, and they gave the exam in 2016, 2017 and passed in 2018, the last result has to update the old result. I am enclosing two documents which i used. One is the 2016 result and the second is the 2017 repeaters csv. LINK TO FILES: https://drive.google.com/open?id=1_5cHRKNYdLBYWLhPw_Z4dn-VgX14Amw2 This what my view looks like template = "uploadstudent.html" data = {} if "GET" == request.method: return render(request, template, data) # if not GET, then proceed csv_file = request.FILES["csv_file_student"] if not csv_file.name.endswith('.csv'): messages.error(request,'File is not … -
django download files from a list (s3 as back-end)
I need to list an html table the content of a S3 bucket and enable the option to download the file. To do so I have done he following: The code shows the list of the bucket files correctly, but I'm not sure how I can write the code to download the files. inventory.html: {% block title %} title{% endblock %} {% block content %} <table class="table table-striped"> <thead> <tr> <th scope="col">Date&nbsp;<a href="?order_by=ord_date&direction=desc">{% load static %}<img src="{% static "arrow.png" %}" width="12" height="12" alt="order desc"></a><a href="?order_by=ord_date&direction=asc">{% load static %}<img src="{% static "sort-down.png" %}" width="12" height="12" alt="order asc"></a></th> <th scope="col">Name&nbsp;<a href="?order_by=ord_source&direction=desc">{% load static %}<img src="{% static "arrow.png" %}" width="12" height="12" alt="order desc"></a><a href="?order_by=ord_source&direction=asc">{% load static %}<img src="{% static "sort-down.png" %}" width="12" height="12" alt="order asc"></a></th> <th scope="col">Size</th> <th scope="col">Action</th> </tr> </thead> <tbody> {% for item in items %} <tr> <td>{{ item.LastModified }}</td> <td>{{ item.Key }}</td> <td>{{ item.Size }}</td> <td><button type="Button" class="btn btn-secondary btn-sm"><a href="?key_download={{ item.Key }}">Download</button></a></td> </tr> {% endfor %} </tbody> </table> {% endblock %} views.py: client = boto3.client('s3') def inventory(request): if request.GET.get('key_download'): url = client.generate_presigned_url('get_object', Params = { 'Bucket':'url_of_the_bucket', 'Key':request.GET.get('key_download')}, ExpiresIn = 86400) return **"I don't know how I can return it"** else: fdc_inventories = client.list_objects_v2(Bucket='url_of_the_bucket') fdc_inventories['Contents'].sort(key=itemgetter('LastModified'), reverse=True) return render(request, 'inventory.html', {'items': … -
How can I do a left join in Django?
What I want to do is: select * from employer e left join person p on p.employer.id = e.id and p.valid = True That means that I will see |employer|null| for any employer that does not have a person working for them and I will see the same thing if there is a person working for them but they are invalid. In django I wish I could do: employers.objects.all().values('id', 'person') and have the value of person show up as None rather than show me the invalid person. -
How can I append the page number in the request endpoint
I am having a URL as below: HTTP Request Method : GET Endpoint: http://localhost:8000/api/<client_id>/getshowscount I am using a paginator class in my Django code. class ShowListPagination(PageNumberPagination): page_size = 10 page_size_query_param = 'page_size' max_page_size = 1000 class ClientShowSongListViewSet(viewsets.ModelViewSet): permission_classes = (DashboardAccess,) serializer_class = ShowCountSerializer pagination_class = ShowListPagination def get_queryset(self): return ShowSong.objects.filter(user = self.request.user) Everything works fine. But, the requirement says that I need to have URL endpoint as below: Endpoint examples: http://localhost:8000/api/<client_id>/getshowscount/?page=1 http://localhost:8000/api/<client_id>/getshowscount/?page=2 By the above endpoint examples, I mean to say that I need to append the page also in the URL depending upon the pages. I checked the paginator class. But I didn't find anything useful. Can anyone suggest some workarounds for the same? -
basic django site gives error as "Not found: /nettrack/
I am totally new to django and stuck with basic learning of django. I have below structure of django project: G:\virtualenvs\Netsite\netmon-- enter image description here I have below urls.py under netmon enter image description here I have below urls.py under nettrack enter image description here This is basic_generic.html And I have below index.html enter image description here Now, whats wrong? I get error as below in the cmd window of "python manage.py runserver" enter image description here Please help. Also, I dont know whether I need any IIS running on my windows desktop machine so as to test site as http:/127.0.0.1:8000/nettrack/ in edge browser. -
How to get large-size scraped data quickly?
I select news from one website and display it on my page. But when I go to the news tab or refresh the page, the page loads data for a while (10 seconds). How can I upload data instantly? I tried to load data, but the problem is that if the text to the article is too large, the page load will still not be instantaneous. Maybe i can upload text in chunks some way? My code: def get_summary(url): new_d = BeautifulSoup(requests.get(url).text, 'html.parser') return '\n'.join(i.text for i in new_d.find('div', {'class':'flexible_content_wrap'}).find_all('p')) def scrape(request): website_url = requests.get("https://loudwire.com/news/").text soup = BeautifulSoup(website_url, "html.parser") more = [] teaser = soup.find_all('div', {'class':'teaser_feed_common'}) for i in teaser: mine = get_summary(i.a['href']) print(mine) more.append(mine) context = {'more_info': more} return render(request, 'music/news.html', context) In advance, thanks for any help. -
cannot resolve keyword 'user' into field - django error
this is the error message I am getting --->Cannot resolve keyword 'user' into field. Choices are: date_joined, email, emailconfirmed, first_name, groups, id, is_active, is_staff, is_superuser, last_login, last_name, logentry, order, password, profile, user_permissions, useraddress, userdefaultaddress, username, userstripe<---- it is highlighting these two pieces of code as key areas as where the problem seems to arise. new_order = Order.objects.get(cart=cart) ///// new_order.user = User.objects.get(user=request.user) all help would be greatly appreciated in solving this! views.py - orders import time import stripe from django.contrib.auth.decorators import login_required from django.conf import settings from django.contrib.auth.models import User from django.shortcuts import render, HttpResponseRedirect from django.urls import reverse # Create your views here. from users.forms import UserAddressForm from carts.models import Cart from .models import Order from users.models import Profile, UserAddress, UserAddressManager from .utils import id_generator stripe.api_key = settings.STRIPE_SECRET_KEY def orders(request): context = {} template = "orders/user.html" return render(request, template, context) @login_required def checkout(request): try: the_id = request.session['cart_id'] cart = Cart.objects.get(id=the_id) except: the_id = None return HttpResponseRedirect(reverse("cart")) try: **new_order = Order.objects.get(cart=cart)** except Order.DoesNotExist: new_order = Order() new_order.cart=cart **new_order.user = User.objects.get(user=request.user)** new_order.order_id = id_generator() new_order.final_total = cart.total new_order.save() except: return HttpResponseRedirect(reverse("cart")) try: address_added = request.GET.get("address_added") except: address_added = None if address_added is None: address_form = UserAddressForm() else: address_form = None current_addresses = … -
syntax error in using SECRET_KEY in __init__py in django
I have read that it is not secure to store the SECRET_KEY in settings.py as its default. So, I decided to store it in my __init__.py. I wrote in __init__.py which is beside settings.py: export SECRET_KEY= 'hf7^vrmc!^agnpba#^+$9ac-@eullgd-=ckq&u1zu$b7nqc)%_' This is the only line in my __init__.py. Then in settings.py I changed the line SECRET_KEY = 'hf7^vrmc!^agnpba#^+$9ac-@eullgd-=ckq&u1zu$b7nqc)%_' into SECRET_KEY = get_env_variable('SECRET_KEY') but when I try to runserver, I receive Syntax error as below: … __init__.py", line 1 export SECRET_KEY= 'hf7^vrmc!^agnpba#^+$9ac-@eullgd-=ckq&u1zu$b7nqc)%_' ^ SyntaxError: invalid syntax What's wrong here? Thank you in advanced. -
django dynamically loading a static file
I am trying to send a static link to a download button. The static link results in a views.py function and will be returned as a dict. in views.py: def some_fct(request): handling the request return render(request,'site.html',{'processed_request': 'name_of_static_file'}) I tried to locate the data in a seperate div and change the href with: <div id="data">{{processed_request}}<\div> <a href="" id="download"><button class="download_btn"><i class="fa fa-download"></i> Download</button></a> <script> let file = document.getElementbyId('data').innerHTML; let file_static = "{% static '${file}' %}" document.getElementById('download').setAttribute("href",file_static); </script> which leads to the console.log https://..../static/%24%7Bfile%7D instead of https://..../static/name_of_static_file How can I access the static_file? -
ImportError: cannot import name 'BaseContact'
I have a problem while running my Django code. File "E:\sophienwald\amocrm\models.py", line 3, in <module> from amocrm import BaseContact, amo_settings, fields, BaseLead ImportError: cannot import name 'BaseContact' But I noticed a strange feature... If I swap "BaseContact" and "BaseLead" it says that compiler can't import BaseLead. "fields" and "amo_setting" work fine. Bit of code from amocrm\models.py: import logging from amocrm import BaseContact, amo_settings, fields, BaseLead from django.conf import settings from django.db import models from django.db.models.signals import pre_save from django.dispatch import receiver from django.utils.functional import cached_property from wagtail.admin.edit_handlers import MultiFieldPanel, FieldPanel from wagtail.contrib.settings.models import BaseSetting from wagtail.contrib.settings.registry import register_setting logger = logging.getLogger(__name__) @register_setting class AmocrmSettings(BaseSetting): PIPELINE_FIELDS = [ ('stay_tuned_pipeline_name', 'stay_tuned_status_name'), ('new_posts_pipeline_name', 'new_posts_status_name'), ('back_call_pipeline_name', 'back_call_status_name'), ] login = models.CharField('Логин', max_length=120, null=True, blank=True) token = models.CharField('Токен', max_length=120, null=True, blank=True) subdomain = models.CharField('Поддомен', max_length=120, null=True, blank=True) run_async = models.BooleanField('Обновлять асинхронно', default=False) # forms.StayTunedContact stay_tuned_pipeline_name = models.CharField('Название воронки', max_length=120, null=True, blank=True) stay_tuned_status_name = models.CharField('Статус при создании', max_length=120, null=True, blank=True) # forms.NewPostsContact new_posts_pipeline_name = models.CharField('Название воронки', max_length=120, null=True, blank=True) new_posts_status_name = models.CharField('Статус при создании', max_length=120, null=True, blank=True) # forms.BackCallContact back_call_pipeline_name = models.CharField('Название воронки', max_length=120, null=True, blank=True) back_call_status_name = models.CharField('Статус при создании', max_length=120, null=True, blank=True) panels = [ MultiFieldPanel([ FieldPanel('login'), FieldPanel('token'), FieldPanel('subdomain'), FieldPanel('run_async'), ], 'Авторизация'), ] -
Show the download button only if file is available on server in Django template (html)
Following code shows the download option on the page whether file is present or not on server. <a href="{%static 'media/reports/finance'%}/sap-daily.csv" download >Download</a> I want to show not available option if the file is not present on server. -
How can I access serializer's field data before its type validation?
How to access the field value before serialization in my serializer (serializers.Serializer) or rest view (UpdateAPIView)? I have something like this: class MySerializer(serializers.Serializer): my_field = serializers.IntegerField() If I try to fill my field with 'test' string, it will immediately raise the ValidationError telling me about wrong data type (expecting an integer number of course). Before that error raise, I want to capture the value and do something with it but I have no idea how and where can I access it. It has an empty string value everywhere. I tried to get it in is_valid() before call super() or with raise_exception=False, but I still can not see it: '_kwargs': {'context': {'format': None, 'request': <rest_framework.request.Request object>, 'view': <rest.views.MyUpdateAPIView object>}, 'data': <QueryDict: {'my_field': ['']}>, 'initial_data': <QueryDict: {'my_field': ['']}>, When I try to find it in my view I can also see nothing: serializer.initial_data <QueryDict: {'my_field': ['']}> request.data <QueryDict: {'my_field': ['']}> When I try to check validate() or validate_my_field() methods, I can not even get there because of the ValidationError I mentioned above. How the serializer validation actually works? What is the order in it and how can I access data before it is "cleaned"? -
Authentication in Django Channels v2 tests with WebSocketCommunicator
In the process of writing tests for my chat consumer I encountered with a problem of being unable to authenticate in tests, using WebSocketCommunicator. I have custom JwtTokenAuthMiddleware that implements authentication in sockets by using token in request query, because as I know, decent authentication with the use of authorization headers is not possible yet. Can you guys advise me on that or provide me with the example code, which I couldn't find across the net ? Btw, my chat is working without problems. Also tests should be perfectly fine, I took the guide from official documentation Django Channels 2.x Testing. --JwtTokenAuthMiddlewate-- class JwtTokenAuthMiddleware: def __init__(self, inner): self.inner = inner def __call__(self, scope): close_old_connections() try: raw_token = scope['query_string'].decode().split('=')[1] auth = JWTAuthentication() validated_token = auth.get_validated_token(raw_token) user = auth.get_user(validated_token) scope['user'] = user except (IndexError, InvalidToken, AuthenticationFailed): scope['user'] = AnonymousUser() return self.inner(scope) JwtTokenAuthMiddlewareStack = lambda inner: JwtTokenAuthMiddleware(AuthMiddlewareStack(inner)) --Example Test-- @pytest.mark.django_db(transaction=True) @pytest.mark.asyncio async def test_trainer_auth_success(): room = await database_sync_to_async(RoomFactory.create)() trainer = room.trainer trainer_token = await sync_to_async(get_token_for_user)(trainer.user) room_url = f'ws/room/{room.id}/' trainer_communicator = WebsocketCommunicator(application, f'{room_url}?t={trainer_token}') connected, _ = await trainer_communicator.connect() assert connected trainer_connect_resp = await trainer_communicator.receive_json_from() assert_connection(trainer_connect_resp, [], room.max_round_time) await trainer_communicator.disconnect() --Traceback of Error-- ___________________________________________________________ test_trainer_auth_success ___________________________________________________________ self = <channels.testing.websocket.WebsocketCommunicator object at 0x7f6b9906f290>, timeout = 1 … -
Django - Login form customization doesn't render
I want to be able to customize my login form but when my login page render, the login form doesn't appear. I tried to do it the way I customized my registration form but I always have the same problem. I'm pretty sure my settings.py and urls.py are correct: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home.apps.HomeConfig', 'inscription.apps.InscriptionConfig', 'profil.apps.ProfilConfig', 'questions.apps.QuestionsConfig', ] from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from inscription import views as i from home import views as h from profil import views as p from questions import views as q urlpatterns = [ path('admin/', admin.site.urls), path('', include('home.urls')), path('accueil/', h.index, name='accueil'), path('inscription/', i.inscription, name='inscription'), path('connexion/', i.connexion, name='connexion'), path('deconnexion/', i.deconnexion, name='deconnexion'), path('profil/', p.profil, name='profil'), path('questions/', q.questions, name='questions') ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I created my login form based on the existing AuthenticationForm (forms.py): from django import forms from django.contrib.auth.models import User from django.contrib.auth import login, authenticate from django.contrib.auth.forms import UserCreationForm, AuthenticationForm class FormulaireConnexion(AuthenticationForm): username = forms.CharField( label = 'Nom de compte' ) password = forms.CharField( label = "Mot de passe", strip = False, widget = forms.PasswordInput(), ) class Meta: model = User fields = ['username','password'] Then I used my … -
Calculate percentage In Django Database Query
I am trying to calculate the total cost of all the services with taxes in the bill using a single query. I don't understand where I am going wrong. MODELS: class Bill(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) number = models.CharField(max_length=100, blank=True) class BillService(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) bill = models.ForeignKey(Bill, related_name='billservices', on_delete=models.CASCADE) service = models.ForeignKey(Service, on_delete=models.CASCADE) class Service(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) business = models.ForeignKey(Business, related_name='services', on_delete=models.CASCADE, blank=True) short_code = models.IntegerField(default=0) class ServiceTax(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) service = models.ForeignKey(Service, on_delete=models.CASCADE, related_name="servicetaxes") tax = models.ForeignKey(Tax, on_delete=models.CASCADE) class Tax(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) business = models.ForeignKey(Business, related_name='taxes', on_delete=models.CASCADE) name = models.CharField(max_length=50) tax = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(100)], default=0) MY QUERY TO GET A SINGLE VALUE, THAT IS TOTAL COST OF THE BILL value = bill.billservices.all() .annotate(sum_of_taxed_percentages=Subquery( Service.objects.filter(billservice=OuterRef('id')) .annotate(total_tax_value=Subquery( ServiceTax.objects.filter(service=OuterRef('id')) .values('tax') .annotate(total_tax=Sum('tax__tax', output_field=FloatField())) .values('total_tax') )).annotate(taxed_value=F('price') + ((F('price') * F('total_tax_value')) / 100)) .values('taxed_value') .annotate(total_services_taxed_value=Sum('taxed_value', output_field=FloatField())) .values('total_services_taxed_value') )) print(value[0].sum_of_taxed_percentages) -
How to CreateView/UpdateView using foreign key in Nested model
Was able to perform CRUD on Branch. However I am stuck in create/update/delete for Feature.. Also when i move to Testcase CRUD, what steps do i need to do.? Please help.. Please Let me know if u need more info regarding this. ....... PS: I am new to django (2 weeks in.. enjoying it :-)). Model: class Branch(models.Model): """Model representing a Branches""" name = models.CharField(max_length=200, db_index=True, unique=True) summary = models.CharField(max_length=200, db_index=True) def __str__(self): """String for representing the Model object.""" return self.name def get_absolute_url(self): """Returns the url to access a particular branch instance.""" return reverse('branch-detail', args=[str(self.id)]) class Feature(models.Model): """Model representing a Feature""" branch = models.ForeignKey(Branch, on_delete=models.SET_NULL, null=True, related_name='features') name = models.CharField(max_length=200, db_index=True, unique=True) def __str__(self): """String for representing the Model object.""" return self.name def get_absolute_url(self): """Returns the url to access a particular feature instance.""" return reverse('feature-detail', args=[self.branch, str(self.id)]) class Testcase(models.Model): """Model representing a Testcase""" feature = models.ForeignKey(Feature, on_delete=models.SET_NULL, null=True, related_name='testcases') name = models.CharField(max_length=200) def __str__(self): """String for representing the Model object.""" return self.name def get_absolute_url(self): """Returns the url to access a detail record for this testcase.""" return reverse('testcase-detail', args=[self.feature.branch, self.feature, str(self.id)]) View: class BranchCreate(CreateView): model = Branch fields = '__all__' success_url = reverse_lazy('index') class BranchUpdate(UpdateView): model = Branch fields = ['name', … -
Django web app Docker - unable to coonect
I am new on Django and Docker and I have a problem to enter site localhost:8000. I built django app and it is working on my local server but I'd like to dockerize my app. So I created two files: Dockerfile : ROM python:3.6.7-alpine ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD ./ /code/ CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] and docker-compose.yml version: '3' services: web: build: . command: python mysite/manage.py runserver 8000 ports: - "8000:8000" My next steps: docker built --tag django_docker:latest . docker run django_docker It's open server, but when I want to open lokalhost:8000 from my browser I can't because of "Unable to connect" Where is my fault? I More about django app : it's project from book Python Crash Course : Learning_log. I'd like to build an image and push it to hub docker, but I am stuck. Thanks for help! -
Django Create Temporary File for Download
I have a model named 'Report Data'. I have a form which will get 'report_name' and will perform a operation. This operation basically loops through objects, every object returned has a file field having '.docx' file, this function will merge all these files into one docx file. After this 'convert' method will convert 'docx' to 'pdf'. I am able to perform this workflow but I need to create a temporary file instead of real files in media directory. My class based view is below class FilesListView(LoginRequiredMixin,ListView): model = ReportData template_name = 'report/myfiles.html' context_object_name = 'reportdata' def get_queryset(self): return ReportData.objects.filter(preparedby=self.request.user).order_by('-date_created') def post(self,request,*args,**kwargs): filtervalue = request.POST.get("report_name","") reportsforPDF = ReportData.objects.filter(reportname=filtervalue) reporturl = settings.MEDIA_ROOT[0:-6] master = Document(reporturl + reportsforPDF.first().document.url) composer = Composer(master) i=0 for object in reportsforPDF: if i>0: doc = Document(reporturl + object.document.url) composer.append(doc) i+=1 storage = settings.MEDIA_ROOT + '/merged/{}.docx'.format(filtervalue) composer.save(storage) pythoncom.CoInitialize() convert(settings.MEDIA_ROOT + '/merged/{}.docx'.format(filtervalue)) context = { 'pdf_url': '/media/merged/{}.pdf'.format(filtervalue) } return render(request, 'report/myfiles.html', context=context) Also how can I use get_query_set inside the post function because my current code returns no objects? -
Django Web Server is not opening open source project
I'm trying to run the Django medicine web-app. it's an open-source project. here's the link https://github.com/jai-singhal/croma when I run this command python manage.py runserver I got this error enter image description here