Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"ModuleNotFoundError("No module named 'MySQLdb'",)" when deploying a OpenLiteSpeed django solution on GCP
I'm testing Google Cloud Platform, where I've deployed a OpenLiteSpeed Django solution with a Ubuntu VM on Google Compute Engine. When it's deployed, everything works like a charm, and I'm able to reach the "Hello, world" starting page. When I try to add my own simple script by changing the views.py file in /usr/local/lsws/Example/html/demo/app to: import MySQLdb from django.shortcuts import render from django.http import HttpResponse def getFromDB(): data = [] db = MySQLdb.connect(host="ip", user="user", passwd="pw", db="db") cur = db.cursor() cur.execute("SELECT * FROM table") for student in students: data.append(student) return data def index(request): return HttpResponse(getFromDB) and access the IP again I'm met with the following traceback and error: Environment: Request Method: GET Request URL: http://ip/ Django Version: 3.0.3 Python Version: 3.6.9 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/usr/local/lsws/Example/html/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lsws/Example/html/lib/python3.6/site-packages/django/core/handlers/base.py", line 100, in _get_response resolver_match = resolver.resolve(request.path_info) File "/usr/local/lsws/Example/html/lib/python3.6/site-packages/django/urls/resolvers.py", line 544, in resolve for pattern in self.url_patterns: File "/usr/local/lsws/Example/html/lib/python3.6/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lsws/Example/html/lib/python3.6/site-packages/django/urls/resolvers.py", line 588, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lsws/Example/html/lib/python3.6/site-packages/django/utils/functional.py", line 48, in __get__ res = … -
invalid literal for int() with base 10: 'educationlevel_api'
why i receive this error? """ invalid literal for int() with base 10: 'educationlevel_api' """ ?? how can i configure this problem?? my Homepage/api/views.py @api_view(['GET', ]) def api_detail_educationlevel(request,slug): try: education = EducationLevel.objects.get(id=slug) except EducationLevel.DoesNotExist: return Response(status=status.HTTP_400_BAD_REQUEST) if request.method == "GET": serializer = EducationLevelSerializer(education) return Response(serializer.data) Homepage/api/serializers.py class EducationLevelSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = EducationLevel field = ('Sequence', 'Description', 'Status') my Homepage/api/urls.py urlpatterns = [ path('<slug>/', api_detail_educationlevel, name="detail"), ] my main urls.py urlpatterns = [ path('api/educationlevel/', include('Homepage.api.urls', 'educationlevel_api')), ] -
Ordering in serializer by using a variable
My variable inside a serializer MySerializer. I want to return it in descending order as per value of du. du = serializers.SerializerMethodField() def get_du(self, obj): modelname = Somemodel.objects.filter('id=id') du = sum(modelname.values_list('t', flat=True)) return du class Meta: model = Anothermodel fields = ('id', 'du' ) The model in APIView i.e Anothermodel and the model in serializermethod is different i.e Somemodel. Is there any other way to do this? My APIView def get(self, request): queryset = Anothermodel.objects.all() serializer = MySerializer(queryset, many=True) return Response({"organization": serializer.data}, status=status.HTTP_200_OK) Output now: { "du": 0, }, { "du" :12 } Expected: { "du": 12, }, { "du" :0 } -
Django overriding save method to save multiple objects at once
i need some help here. I'm trying to create multiple objects at once when saving in admin panel. But the problem is, only the last value in the loop is being saved. I tried setting the primary key to None class Seat(models.Model): seat = models.CharField(default='Seat', max_length=5, unique=True, primary_key=False) available = models.BooleanField() theater = models.ForeignKey(Theater, on_delete=models.CASCADE) def clean(self): if model.objects.count() >= self.theater.capacity: raise ValidationError(' - Maximum seats exceeded!') def save(self, *args, **kwargs): seats_name = [] row_label = [chr(letter) for letter in range(65, 91)] row_track = 0 row_range = 10 col_range = self.theater.capacity // row_range col_track = 0 for n in range(self.theater.capacity): row_track += 1 if row_track > row_range: row_track = 1 col_track += 1 display = "{} | {}-{}".format(self.theater, row_label[col_track], row_track) seats_name.append(display) for seat in seats_name: self.seat = seat super(Seat, self).save(*args, **kwargs) def __str__(self): return self.seat -
while connecting to MicrosoftSQL server using Django facing django.db.utils.OperationalError:
drivers available with me **python shell** '''In [2]: pyodbc.drivers()''' **Output:** **Out[2]: ['SQL Server']** code in settings.py django: **Settings.py in django** '''# Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'dbname', 'HOST': 'ansqlserver.database.windows.net', 'USER': 'test', 'PASSWORD': 'Password', 'OPTIONS': { 'driver': 'SQL Server', } }''' **ERROR:** **Trying to connect to MicrsoftSQL server facing below error** File "C:\Local\Programs\Python\Python37\lib\site-packages\sql_server\pyodbc\base.py", line 314, in get_new_connectiontimeout=timeout) django.db.utils.OperationalError: ('08001', '[08001] [Microsoft][ODBC SQL Server Driver]Neither DSNnor SERVER keyword supplied (0) (SQLDriverConnect); [08001] [Microsoft][ODBC SQL Server Driver]Invalid connection string attribute (0)') -
Emails Not Sending in Django
Before I explain my issue, I first want to clarify that I feel as though I've tried more or less every solution I've seen on Stack Overflow and none of them have worked for me. The issue I'm experiencing is that no emails are being sent when a user requests for a password reset. I'll add some details/context below. settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get("EMAIL_ADDRESS") EMAIL_HOST_PASSWORD = os.environ.get("EMAIL_PASSWORD") I've added my email address and password into my env.py file and I have actually received a notification on my phone notifying me that someone is trying to access my account e.g. an email is trying to be sent from another source. I've also turned App Access on Google off. I'm lost for ideas at this point so any support would be greatly appreciated! -
How do I mock a function in Django?
I expect the following call to which_user to return self.user no matter what is passed into it but it's behaving as if it is not mocked at all. def test_user_can_retrieve_favs_using_impersonation(self): with mock.patch('impersonate.helpers.which_user', return_value=self.user): user = which_user(self.user2) What am I doing wrong here? I imported which_user like so: from impersonate.helpers import which_user if that helps. -
How to implement OAuth2 in Django with Google and Facebook auth by graphql authentication?
I am working on a Django project and I want to implement an authentication system which uses graphql api. The authentication should have an OAuth2.0 implementation bay email and password. It should also use social authentication options like Google and Facebook auth. Django allauth package is the most popular social authentication pakage but I don know how to implement it with graphql. -
View Wagtail pdf documents in new tab
I have tried following for opening Wagtail documents in view mode in new tab. Wagtail document links downloading instead of displaying as a page using wagtail hook: before_serve_method: nothing happens https://github.com/wagtail/wagtail/issues/4359#issuecomment-372815142 Remove "attachment" from response's Content-Disposition and "a href={row.url} target="_blank" rel="noopener">{row.title}" in jsx. opens the document in view mode(same tab) in Firefox and IE but not in Chrome? Not sure why browsers response is different and setting target="_blank" doesn't open in new tab for any browser. Setting attachment: False https://github.com/wagtail/wagtail/blob/cfc2bc8470ab16ddfc573e009e9aaf8c3d240fff/wagtail/utils/sendfile.py#L39 This clearly mentions: If attachment is True the content-disposition header will be set. This will typically prompt the user to download the file, rather than view it: Nothing happens. Firstly, if someone can help with "Remove "attachment" from response's Content-Disposition" approach on why Chrome still pop-up download and pdf's open in view mode in Firefox and IE? The next question is about "a href={row.url} target="_blank" rel="noopener">{row.title}" in jsx. Is there something wrong with this? I'm reloading webpack after change and cleared the cache. -
Django show static image based on model value
I have a DetailView in Django that gets the input from a model instance. I also have an images folder at the path static/images/nba_players containing a picture for each player in the format playername.jpg (ie; russellwestbrook.jpg) Now, say in the DetailView the model instance has the player attribute "Russell Westbrook." How can I get the HTML to find the picture for the player represented in the model instance? My initial thought is to strip the player name string of spaces and capital letters in views.py and pass it in as context data. But then I still don't know how in the HTML to reference that specific image. Any help would be great. -
how to set footer in pdf using python (django with pisa)
I tried to set footer on first page only by using pisa official documentation but it comes in all pages so please suggest how to apply footer on first page of pdf -
Django Model Foreign Keys ManyToManyField and Organizations that are members of other Organizations
I've been teaching myself django, and don't have a background in databases. I looked up entity relationship diagrams and have been reading the django manual and the below model seems to work, but is it the "right way" to do it? I have organizations that can have members, but the organizations can also be be parts of organizations, and members don't have to be part of an organization. The organizations and member companies can also have multiple locations. (Yes this really happens with industry consortiums...) Each may or may not have training materials. So in the class Organization I couldn't call itself, but I could have it be a member_of something in the member class. So what I came up with for a model and it seems to compile and is accessible in the admin interface. class Address(models.Model): # one HQ address, but could have other locations #name could come from either Organization or from Member HQ_address=models.BooleanField() country_code = models.CharField(max_length=2,default='') city =models.CharField(max_length=100,default='') url=models.URLField(max_length=200,default='') email=models.EmailField(max_length=254,default='') class Resource(models.Model):# can have 0 to many of several types of resources #books = models.ManyToManyField(Books) #videos = models.ManytoManyField(Videos) #courses = models.ManytoManyField(courses) pass class Member(models.Model): # a member by itself is not an organization # use the … -
Django Rest Framework Not Null Constraint
When i try to create a new by post by posting the following Json: { "title": "This is serialzer title", "content": "This is serialzer content", } I get the following error: NOT NULL constraint failed: blog_post.views Models.py from django.db import models from django.contrib.auth.models import User from django.utils.timezone import now # Create your models here. class Post(models.Model): sno = models.AutoField(primary_key=True) title = models.CharField(max_length=255) content = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) views = models.IntegerField() slug = models.CharField(max_length=100) timeStamp = models.DateTimeField(default=now) def __str__(self): # return self.title + ' by ' + self.author return self.title + ' by ' + self.author.username class BlogComment(models.Model): sno = models.AutoField(primary_key=True) comment = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True) timeStamp = models.DateTimeField(default=now) def __str__(self): return self.comment[0:13] + "..." + " by " + self.user.username views.py @api_view(['POST']) def api_create_blog_view(request): user = User.objects.get(pk=1) blog_post = Post(author=user) if request.method == "POST": serializer = PostSerializer(blog_post, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializer.py from blog.models import Post from rest_framework import serializers class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ['title', 'content'] I don't know how to solve this please help me to solve this error.DB has already been cleared. … -
django forms and request in same http page
OK so I'm trying to create a page that will have a search form of Well, I get the contents of the search in the page ex: (http://127.0.0.1:8000/wellsheet/ODN20) I used this code urls.py file path('wellsheet/<slug:Evt_id>', views.wellsets, name='WellSheetg'), views.py def wellsets(request, Evt_id): serchedWl = WellSheets.objects.filter(WellID__WellID__exact=Evt_id) context ={ 'title': 'Eventstopost', 'Wellslist':serchedWl, 'WIDSHT':Evt_id, } return render(request, 'Home/WELLINFO/W_TchD/wellshts.html', context) in addition to this page I want to add another well ,and I have a model form to add in same page using crispy. urls.py path('wellsheet/<slug:WeelN>/', views.welshetad2.as_view(), name='AddWellSheet'), views.py class welshetad2(LoginRequiredMixin, CreateView): model = WellSheets template_name = 'Home/WELLINFO/W_TchD/wellshts.html' form_class = UploadWSF2 def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) but in my page I can't render the crispy form <div class="border p-3 mb-3 mt-3 w3-round-large w3-light-grey border-dark"> <form method="POST"> {% csrf_token %} <div class="form-row"><div class="form-group mb-0"> {{ form.as_p }} </div></div> this is my page page My goal is to see a page like this My Goal -
django template add two variables
how can I add two or more variables in django template? here is my template code: {% for cap in capital %} {{cap.capital_type}} {{cap.capital_amount}} {% endfor %} Total Capital: {{total_capital}} where {{total_capital}} will be sum of cap.capital_amount -
Django - weird debug output when using migrations management commands after installing matplotlib
Running GeoDjango in a Docker container - have added additional libraries via pip in the Dockerfile, and am now experiencing unwanted console output whenever I invoke any of the migrations commands, e.g. manage.py showmigrations/makemigrations/migrate. The output is as follows: user@host:/src$ ./manage.py showmigrations CONFIGDIR=/home/django/.config/matplotlib (private) matplotlib data path: /usr/local/lib/python3.7/site-packages/matplotlib/mpl-data matplotlib data path: /usr/local/lib/python3.7/site-packages/matplotlib/mpl-data loaded rc file /usr/local/lib/python3.7/site-packages/matplotlib/mpl-data/matplotlibrc matplotlib version 3.2.1 interactive is False platform is linux loaded modules: ['sys', 'builtins', '_frozen_importlib', '_imp', '_thread', '_warnings', '_weakref', 'zipimport', '_frozen_importlib_external', '_io', 'marshal', 'posix', 'encodings', 'codecs', '_codecs', ... Comprehensive modules listing snipped, it continues: Using fontManager instance from /home/django/.cache/matplotlib/fontlist-v310.json Loaded backend qt5agg version unknown. Loaded backend tkagg version unknown. Loaded backend agg version unknown. Loaded backend agg version unknown. Found GEOS DLL: <CDLL '/usr/local/lib/python3.7/site-packages/shapely/.libs/libgeos_c-5031f9ac.so.1.13.1', handle 5608f64e4c40 at 0x7f22a5aaaf10>, using it. Trying `CDLL(libc.so.6)` Library path: 'libc.so.6' DLL: <CDLL 'libc.so.6', handle 7f22c4809000 at 0x7f22aef3b650> GDAL_DATA not found in environment, set to '/usr/local/lib/python3.7/site-packages/fiona/gdal_data'. PROJ data files are available at built-in paths Entering env context: <fiona.env.Env object at 0x7f22a0798450> Starting outermost env No GDAL environment exists New GDAL environment <fiona._env.GDALEnv object at 0x7f22a0798490> created Logging error handler pushed. All drivers registered. GDAL_DATA found in environment: '/usr/local/lib/python3.7/site-packages/fiona/gdal_data'. PROJ data files are available at built-in paths Started GDALEnv <fiona._env.GDALEnv object at … -
Best Practice Using Django Signal (For user authentication?)
I am new to Django and want to know deeper about the concept of signals. I know how it works but really don't understand when should one really use it. From the doc it says 'They’re especially useful when many pieces of code may be interested in the same events.' What are some real applications that use signals for its advantage? e.x. I'm trying to make a phone verification after user signup. Because it can be integrated inside the single app and the event that interested for the signal is only this 'verify' function, therefore I don't really need signal. I can just pass the information from one view to the other, rather than using pre_save signal from the registration. I'm sorry if my question is kind of basic. But I really want to know some insight what is the real application, in which many codes interested in one particular event and what are some trade off in my application. Thanks!! -
Django SECRET_KEY environmental variable always empty
In mysite/settings.py I have: SECRET_KEY = os.environ["SECRET_KEY"] Using the GUI Control Panel ---> System Properties ---> Advanced ---> Environmental Variables, I have set the user environmental variables: Variable Value SECRET_KEY 123456 But am still getting the key is empty error when I run manage.py Failed to get real commands on module "mysite": python process died with code 1: Traceback (most recent call last): File "C:\Program Files\JetBrains\PyCharm 2020.1.2\plugins\python\helpers\pycharm\_jb_manage_tasks_provider.py", line 25, in <module> django.setup() File "C:\Users\super\Desktop\GitHub\Django_Tutorial_Site\mysite\venv\lib\site-packages\django\__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "C:\Users\super\Desktop\GitHub\Django_Tutorial_Site\mysite\venv\lib\site-packages\django\conf\__init__.py", line 76, in __getattr__ self._setup(name) File "C:\Users\super\Desktop\GitHub\Django_Tutorial_Site\mysite\venv\lib\site-packages\django\conf\__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File "C:\Users\super\Desktop\GitHub\Django_Tutorial_Site\mysite\venv\lib\site-packages\django\conf\__init__.py", line 142, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\super\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\super\Desktop\GitHub\Django_Tutorial_Site\mysite\mysite\settings.py", line 11, in <module> SECRET_KEY = os.environ["SECRET_KEY"] File "C:\Users\super\AppData\Local\Programs\Python\Python38-32\lib\os.py", line 675, in __getitem__ raise KeyError(key) from None KeyError: 'SECRET_KEY' -
Django 3 when sending a letter to mail, images in the letter are not displayed, how to fix it?
subject = name_cinema html_message = render_to_string('app_template/mail_template.html', context) plain_message = strip_tags(html_message) from_email = 'From <example12090@gmail.com>' to = email mail.send_mail(subject, plain_message, from_email, [to], html_message=html_message) Layout mail_template.html, the problem is iz from the image, iz from the content of all the norms it is shown less than 4 varianti, there, de invoking the power of the image. {% load static%} connection <img src="{% static 'img/1234.png' %}" alt="1"> <img src="{% static 'img/1.png' %}" alt="2"> <img src="../../1234.png" alt="3"> 4<img src="https://www.meme-arsenal.com/memes/579eb482a8540ee55b0bf3db8695a783.jpg" alt="4"> enter image description here -
Why I can't import a file from a Django app into the urls.py file?
I'm trying to do a Django tutorial but I keep getting the same error I don't know why, I have follow every step in the same way. ERROR: { "resource": "/Users/mycomputer/Documents/Programacion/Python/Curso Django/password_generator_p/password_generator/urls.py", "owner": "_generated_diagnostic_collection_name_#0", "code": "unresolved-import", "severity": 4, "message": "unresolved import 'generator'", "source": "Python", "startLineNumber": 18, "startColumn": 6, "endLineNumber": 18, "endColumn": 15 } Import Settings I've already tried with: - from . import views - from . import views - from .. import views - from password_generator.generator import views - from generator.views import views - from password_generator_p import generator / from generator import views -
Having trouble making a view with 2 forms
I made a django view and I am able to display my configuration the way I want to except that the answers to my attributes are not editable. I have tried a few different ways to get this to work and am struggling to find a way to get the form to allow my answers to be changable. My Model class Configuration(models.Model): name = models.CharField(max_length=100, blank=True, null=True) config_type = models.ForeignKey('ConfigType', on_delete=models.PROTECT, null=True) company = models.ForeignKey('companies.Company', on_delete=models.PROTECT, blank=True, null=True) creation_date = models.DateTimeField(auto_now_add=True, blank=False, null=True) updated = models.DateTimeField(auto_now=True) sla = models.ForeignKey('SLA', on_delete=models.PROTECT, blank=True, null=True) install_date = models.DateField(auto_now_add=False, auto_now=False, blank=True, null=True) purchase_date = models.DateField(auto_now_add=False, auto_now=False, blank=True, null=True) purchase_price = models.DecimalField(decimal_places=2, max_digits=1000, blank=True, null=True) warranty_exp = models.DateField(auto_now_add=False, auto_now=False, blank=True, null=True) end_of_life = models.DateField(auto_now_add=False, auto_now=False, blank=True, null=True) #vendor = models.ForeignKey('companies.Company', on_delete=models.PROTECT, blank=True, null=True) manufacturer = models.ForeignKey('Manufacturer', on_delete=models.PROTECT, blank=True, null=True) mfg_part = models.CharField(max_length=50, blank=True, null=True) model_number = models.CharField(max_length=50, blank=True, null=True) serial_number = models.CharField(max_length=250, blank=True, null=True) tag_number = models.CharField(max_length=50, blank=True, null=True) notes = models.TextField(max_length=1024, blank=True) def __str__(self): return self.name def get_absolute_url(self): return reverse("configurations:configuration-update", kwargs={"id": self.id}) class Manufacturer(models.Model): name = models.CharField(max_length=50, blank=False) incative = models.BooleanField(default=False) def __str__(self): return self.name class SLA(models.Model): name = models.CharField(max_length=25, blank=False) def __str__(self): return self.name class ConfigType(models.Model): name = models.CharField(max_length=50, blank=False) inactive = models.BooleanField(default=False) … -
Django/Jquery inlineformset: why add-row button is hidden when using max_num option i my formset?
I am developping a Django project and I use nested inlineformset with jQuery to get add-row and delete-row buttons. It works but I would like to use inlineformset options extra=3 and max_num=4. The problem is that, with max_num option, the add-row button is hidden (as I can see in developer tool). I don't understand why. My first attempt was to display the button using JQuery (display=False -> display=True). The button is displayed but when I click it add a row the button disappeared... It should have a better way to do that... forms.py NAME = Thesaurus.options_list(2,'fr') ACCESS = Thesaurus.options_list(3,'fr') ApplicationFormset = inlineformset_factory( UtilisateurProjet, Application, #Utilisateur, Application, fields=('app_app_nom','app_dro'), widgets={ 'app_app_nom': forms.Select(choices=NAME), 'app_dro': forms.Select(choices=ACCESS) }, extra=3, can_delete=True, max_num=4, ) js <script src="{% static 'project/js/jquery.formset.js' %}"></script> <script> $('.link-formset').formset({ addText: 'Ajouter', deleteText: 'Supprimer', prefix: '{{ application.prefix }}' }); </script> -
Docker-compose can not connect mysql with django
when I use docker-compose to connect mysql with my djangoapp,I got this error:web_1 | django.db.utils.OperationalError: (2005, "Unknown MySQL server host 'db' (-2)") and this db_1 seems also wrong ,enter image description here this is my Dockerfile FROM python:3.7 ENV PYTHONUNBUFFERED 1 RUN mkdir /myblog RUN mkdir /myblog/db WORKDIR /myblog RUN pip install pip -U -i https://pypi.tuna.tsinghua.edu.cn/simple ADD ./requirements.txt /myblog/ RUN pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple ADD . /myblog/ this is my docker-compose FROM python:3.7 ENV PYTHONUNBUFFERED 1 RUN mkdir /myblog RUN mkdir /myblog/db WORKDIR /myblog RUN pip install pip -U -i https://pypi.tuna.tsinghua.edu.cn/simple ADD ./requirements.txt /myblog/ RUN pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple ADD . /myblog/ [root@VM_0_12_centos lshblogs]# cat docker-compose.yml version: "3.0" services: db: image: mysql:5.7 expose: - "3306" volumes: - ./db:/var/lib/mysql environment: - MYSQL_DATABASE=lsh_blog - MYSQL_ROOT_PASSWORD=11111111 web: build: . command: python ./manage.py runserver 0.0.0.0:8000 volumes: - .:/myblog ports: - "8000:8000" depends_on: - db this is my database settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'lsh_blog', 'USER': 'root', 'PASSWORD': '11111111', 'HOST': 'db', 'PORT': '3306', } } this is the error stack db_1 | 2020-06-15 15:23:41+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.30-1debian10 started. db_1 | 2020-06-15 15:23:41+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql' db_1 | 2020-06-15 … -
Django - [WinError 10061] No connection could be made
Sorry, I know theres a lot of content here and elsewhere on the internet, but lets go... I deployed my application on a local server. Everything is working perfectly, but when trying to generate a PDF in the administration area, return this error. I searched about it and all I can find is about email sending settings. Although my generate_curriculo_pdf doesn't use sending emails, does it really have something related? Does anyone have any idea? ConnectionRefusedError at /admin/main/vagasusuarios/1/actions/generate_curriculo_pdf/ [WinError 10061] No connection could be made because the target machine actively refused it Request Method: GET Request URL: http://192.168.109.217/admin/main/vagasusuarios/1/actions/generate_curriculo_pdf/ Django Version: 2.2.13 Python Executable: c:\python\python.exe Python Version: 3.5.0 Python Path: ['.', 'c:\\python\\python35.zip', 'c:\\python\\DLLs', 'c:\\python\\lib', 'c:\\python', 'c:\\python\\lib\\site-packages', 'c:\\python\\lib\\site-packages\\setuptools-47.1.1-py3.5.egg', 'C:\\inetpub\\wwwroot\\settings'] Server time: Seg, 15 Jun 2020 12:36:45 -0300 Installed Applications: ['main', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'localflavor', 'django.contrib.humanize', 'django_object_actions', 'bootstrap4', 'ckeditor', 'ckeditor_uploader'] Installed Middleware: ['whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "c:\python\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "c:\python\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "c:\python\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "c:\python\lib\site-packages\django\utils\decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "c:\python\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "c:\python\lib\site-packages\django\contrib\admin\sites.py" … -
How to redirect back to current page in Django once a button is clicked?
Currently this view redirects back to homepage. def wishlist(request, title_slug): obj = get_object_or_404(Listing, slug=title_slug) profile = Profile.objects.all().filter(user=request.user).first() profile.wishlist.add(obj) return HttpResponseRedirect('/') I have this button in list view and detail view: <a href="{% url 'listing:wishlist' listing.slug %}"> <i class="fas fa-heart"></i> </a> No matter where the user adds an item to wishlist, it should be redirected back to that list view or detail view. Thank you