Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Advanced Tutorial: Error when trying run server or migrate app after successfully installing own package
I'm following the Advanced Django Tutorial and have managed to package my polls app into another directory outside of mysite directory. I run pip install --user django-polls/dist/django-polls-0.1.tar.gz inside the directory which my django-polls app is at and manage to successfully install it. However, when I try to run python manage.py runserver inside the mysite directory I get the following message on my terminal: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Users/*USER*/django/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/*USER*/django/django/core/management/__init__.py", line 357, in execute django.setup() File "/Users/*USER*/django/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/*USER*/django/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/Users/*USER*/django/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/Users/*USER*/anaconda3/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'polls.apps' I tried running python manage.py migrate and get the same message. Could someone explain what's happening here? I'm running the latest version of Django. Thanks in advance for your time. -
Problems with CORS in Django
I'm trying to enable CORS in my app (React is front-end and Django is server). I have included this lines: INSTALLED_APPS = [ . . 'corsheaders' . . ] and this MIDDLEWARE = [ . . 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', . . ] Also have added CORS_ORIGIN_ALLOW_ALL = True But it still doesn't work. Access to fetch at 'http://localhost:8000/mentor_list' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. What is wrong? -
Delete a django application
I have an app in my django project that I'd rather do away with. I have removed all models and removed all reference to the app from all other apps but if when I remove the app from my settings.INSTALLED_APPS I get the below error. Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0000028F0C408C80> Traceback (most recent call last): File "C:\Users\Chidimmo\.virtualenvs\funnshopp-Ze7zokAC\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\Chidimmo\.virtualenvs\funnshopp-Ze7zokAC\lib\site-packages\django\core\management\commands\runserver.py", line 120, in inner_run self.check_migrations() File "C:\Users\Chidimmo\.virtualenvs\funnshopp-Ze7zokAC\lib\site-packages\django\core\management\base.py", line 442, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\Chidimmo\.virtualenvs\funnshopp-Ze7zokAC\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\Chidimmo\.virtualenvs\funnshopp-Ze7zokAC\lib\site-packages\django\db\migrations\loader.py", line 49, in __init__ self.build_graph() File "C:\Users\Chidimmo\.virtualenvs\funnshopp-Ze7zokAC\lib\site-packages\django\db\migrations\loader.py", line 226, in build_graph self.add_external_dependencies(key, migration) File "C:\Users\Chidimmo\.virtualenvs\funnshopp-Ze7zokAC\lib\site-packages\django\db\migrations\loader.py", line 191, in add_external_dependencies parent = self.check_key(parent, key[0]) File "C:\Users\Chidimmo\.virtualenvs\funnshopp-Ze7zokAC\lib\site-packages\django\db\migrations\loader.py", line 174, in check_key raise ValueError("Dependency on unknown app: %s" % key[0]) ValueError: Dependency on unknown app: service I want to remove every reference to that app from the database as well as removing it from settings.INSTALLED_APPS. I performed a search of django docs but couldn't find anything to that effect. All previous solutions I found here on SO relied on sqlclear which is no longer supported by django. How should I go about it? I'm using Django==2.1.3 -
Saleor Product Bulk upload script
I am new to saleor and is creating a ecommerce platform. I have downloaded saleor and made it up and running. I have 1000+ products to add. To add manually is a big nightmare. Checking if there is any scripts or ways to bulk upload products along with details (like images etc) to the saleor -
TypeError: post() missing 1 required positional argument: 'self' [duplicate]
This question already has an answer here: How can I decorate an instance method with a decorator class? 3 answers So I'm trying to create a proxy decorator that you pass in a helper so I can use it across multiple django views. So proxying is working fine but if I don't want it to proxy and run the view I get a traceback: TypeError: post() missing 1 required positional argument: 'self'. class HttpLocalProxy(object): def proxy(self, *args): if self.proxy_helper.should_proxy(self._get_request_object(*args)): <do proxy stuff> return self.fn(request=*args) def __init__(self, proxy_helper: ProxyInterface) -> None: self.proxy_helper: ProxyInterface = proxy_helper def __call__(self, fn) -> typing.Callable: self.fn: typing.Callable = fn return self.proxy I decorate the django view. class MyView(rest_framework.views.APIView): @iaw_api.helpers.local_proxy.HttpLocalProxy(monitor.helpers.local_proxy.MonitorProxyHelper(django.conf.settings.API_MONITOR_PROXY)) def post(self, request): <rest of code> This is because I don't have an instance of the class to run the post. I tested the theory and I can create an instance and pass it with the args back but it won't always be the same view class so I need to pass it in. I can't create an instance of itself as a class variable and pass it in with the helper so I'm stuck. I've got a feeling there may be a simple solution but I … -
Dropdown Menu in a Django-Tables2 cell
I have a table generated by Django-tables2 which all works fine. The first column is formatted as a button which removes the current line from the table. However I now want to have other functions such as copy etc. I could simply add a new button for each possible function but then I'd end up with a table of buttons and no room for data. So I would like to replace the first button with a dropdown menu of the various functions. It seems fairly straightforward to add the menu header, but I can't work out how or where to add my unordered list for the menu items. Has anyone tried to do this or does anyone know if this is even possible? Code for my button as cell. class TaskTable(ColumnShiftTable): remove = tables.LinkColumn('tasks:deletetask', args=[A('pk')], text='Delete', orderable=False, empty_values=(), attrs={'th':{'class': 'nocolor'},'a':{'class':'btn btn-danger'}}) Code changed to be a menu option class TaskTable(ColumnShiftTable): menu = tables.LinkColumn(text='Options', attrs={'th':{'class': 'nocolor'},'a':{'href':'#','class':'dropdown-toggle','data-toggle':'dropdown'}}) How do I expand the second lot of code above to incorporate my menu items list. -
Django, form.save(), doesn't save on the admin page.
I don't know why the variables from the register form doesn't store in django admin page! I'm confused. Thank you for read this, I really appreciate this. :) //htmlsnippet.html {% block content %} <h1>Sign up</h1> <form class ="site-form" action="register/" method="post"> {% csrf_token %} {{form}} <input type="submit" value="Signup"> </form> {% endblock %} //home.html {% extends "register/header.html" %} {% block content %} {% include "register/includes/htmlsnippet.html" %} {% endblock %} //views.py from django.shortcuts import render,redirect from django.http import HttpResponse from django.contrib.auth.forms import UserCreationForm # Create your views here. def index(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() return redirect("/personal") else: form = UserCreationForm() return render(request, 'register/home.html',{'form':form}) -
How to use restored schema in postgres for a multi tenant djangon application?
I got the database (postgres) dump from production and restored on development of a multi tenant django application. I created a new database and edited settings. But when every time I run the application on dev, I am getting below error. Case is same for every migration command (e.g. makemigrations, migrate, migrate_schema etc.) "python manage.py <<....>>". django.db.utils.ProgrammingError: relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... Can anyone help how I can use restored data on development server? -
Is there a way to debug javascript files in a Django project using VS code?
I have a django project that uses some React apps (via bundling from Webpack) besides the usual javascript files. I would like to debug these javascript files (both type of them) inside Visual Studio Code (without using DevTools F12 from the browser). There are some sites that explain how to debug javascript files using the Debugger for Chrome extension, but I could not find anywhere how to set this for a django project. I have followed the steps indicated in Cannot debug in VSCode by attaching to Chrome, but instead of running serve -p 8080, I run python manage.py runserver (by default it runs in port 8000). Then, I have added the following launch option: { "version": "0.2.0", "configurations": [ { "type": "chrome", "request": "launch", "name": "Launch Chrome against localhost", "url": "http://localhost:8000", "webRoot": "${workspaceRoot}" } } However, when I launch it, it does not catch any breakpoint set in the javascript files. PS: ${workspaceRoot} points to the root of my django structure. -
Add a column from another object to an existing listview
I have an existing listview and I want to add a new column(contactDate) from another object which will be soratble. my objects are: class Left(models.Model): ref = models.CharField(max_length=16, blank=True) customer = models.CharField(max_length=100, blank=True) days = models.PositiveIntegerField(blank=True, null=True) business_classification = models.CharField(max_length=15, blank=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) def __unicode__(self): return u'%s in %s (%d days)' % ( self.customer, self.days_in_delay ) class Action(models.Model): left = models.ForeignKey(Left, related_name='actions') personal_use = models.ForeignKey(User, related_name='actions') phone_calls = models.BooleanField(default=False) next_contact_date = models.DateTimeField(blank=True, null=True) description = models.CharField(max_length=100) def __unicode__(self): return self.description As a newbie in python I haven't found a good example till now that fits my solution. Any orientation is well-appreciated. -
Django Rest Framework how to post date field
I want to post JSON request with field date: { "date":"2015-02-11T00:00:00.000Z" } It's the string is automatically converted from Datetime object and I don't want to crop the part T00:00:00.000Z manually at frontend. But if I post such request, Django Rest Framework validator of DateField will say me, that date has invalid format. What is the right way to solve this problem? -
not getting results in django search
I created a simple django blog where i want to provide a search option. so , I tried and didnt even get any error. but the problem is I didn't even get any search results too. its showing empty page even if there is a post related to that query. help me out guys. Here my code goes...... views.py class home_view(ListView): model = home_blog_model template_name = "home.html" context_object_name = "posts" paginate_by = 8 ordering = ['-date'] def search(request): query = request.GET.get("key") if query: results = home_blog_model.objects.filter(Q(title__icontains=query)) else: results = home_blog_model.objects.filter(status="Published") return render(request , "home.html" , {"query":query}) urls.py from django.urls import path from . import views from django.contrib.auth.views import LoginView , LogoutView urlpatterns = [ path("" , views.home_view.as_view() , name="blog-home"), path("posts/<int:pk>/" , views.detail_view , name="detail"), path("admin/login/" , LoginView.as_view(template_name="admin-login.html") , name="admin-login"), path("admin/logout/" , LogoutView.as_view() , name="admin-logout"), path("admin/post/create/" , views.create_post_view , name="create_post"), path("post/search/" , views.search , name="search_post"), ] models.py from django.db import models class home_blog_model(models.Model): title = models.CharField(max_length=100) summary = models.CharField(max_length=300) content = models.TextField() date = models.DateTimeField(auto_now=True) def __str__(self): return self.title home.html <div align="right"> <form class="form-group" method="GET" action="{% url 'search_post' %}"> <input type="text" name="key" placeholder="search........" value="{{request.GET.key}}"> <button class="btn" type="submit">Search</button> </form> </div> thanks in advance ! -
How do I retain selected option after submit?
Is there a way to retain the selected option from a drop down list that is using a for loop? views.py: ... queryC = request.GET.get('clientList', '') queryT = request.GET.get('topicList', '') topicList = Topic.objects.all().order_by('Name') clientList = ClientDetail.objects.all().order_by('Client_name') ... return render(request, 'app/search_es20.html', { "responses": responses, "query": q, "queryR": queryR, "noOfResults": resultsCount, "username": username, "topicList": topicList, "clientList": clientList, "queryC": queryC, "queryT": queryT, }) html: Topic <select name="topicList"> <option value="empty"></option> {% for element in topicList %} <option value={{element.Name}}>{{ element.Name }}</option> {% endfor %} </select> Client <select name="clientList"> <option value="empty"></option> {% for element in clientList %} <option value={{element.Client_name}}>{{ element.Client_name }}</option> {% endfor %} </select> I have tried using IF statements but it's not doing it properly -
unsupported operand type(s) for -: 'NoneType' and 'datetime.datetime'
is giving this error, but before it was not, I do not know what happened Model.py class MovRotativo(models.Model): checkin = models.DateTimeField(auto_now=False, null=False, blank=False) checkout = models.DateTimeField(auto_now=False, null=True, blank=True) valor_hora = models.DecimalField(max_digits=5, decimal_places=2) veiculo = models.ForeignKey(Veiculo, on_delete=models.CASCADE) pago = models.BooleanField(default=False) def horas_total(self): return math.ceil((self.checkout - self.checkin).total_seconds() / 3600) def total(self): return self.valor_hora * self.horas_total() def __str__(self): return self.veiculo.placa views.py @login_required def movrotativos_novo(request): form = MovRotativoForm(request.POST or None) if form.is_valid(): form.save() return redirect('core_lista_movrotativos') -
How to get contents of curl uploaded file in django
I'm using Django 2.1.1 and would like to upload a file using this curl command: curl -i -b cookies.txt -c cookies.txt -e https://neon/accounts/login/ \ --cert client.crt --key client.key -F "name=@afile" \ -H "X-CSRFToken: 9rQMPHGdPJHLVbSEmhwXLc1m9i1KIQVVenRPqP2JkqrldKgWX4GMahOET7pk5cnw" \ -H "Content-type: multipart/form-data" \ -X POST -F 'test=blaat' https://neon/test/ the url goes to the following view: def test(request): response = pprint.pformat(request.FILES, indent=4) return HttpResponse(response) The result of curl is: HTTP/1.1 100 Continue HTTP/1.1 200 OK Server: nginx/1.10.3 (Ubuntu) Date: Thu, 22 Nov 2018 14:37:03 GMT Content-Type: text/html; charset=utf-8 Content-Length: 72 Connection: keep-alive X-Frame-Options: SAMEORIGIN Strict-Transport-Security: max-age=63072000; includeSubdomains X-Frame-Options: DENY X-Content-Type-Options: nosniff { 'name': <InMemoryUploadedFile: afile (application/octet-stream)>} So how can I get the contents of 'afile' in a str variable in Django... I tried request.FILES['file'].chunks() but don't really have an idea of what I am trying here. Also writing the contents to a file on the server: no idea. The main thing is to get it into a variable so I can for example parse JSON from that file. The login, SSL certificates and authentication all works fine. That's not an issue. -
Django show exchange rate via xml file
I want to show the US dollar currency on my website. There is have xml file for currency; http://www.tcmb.gov.tr/kurlar/today.xml But I have no idea how to get this information in. For example, how I can take USD and EUR data on my website. (I would be very happy if you give the sample code.) Thank you very much in advance. Perhaps it may be better to print this information into mysql on a daily. And after this i can read this informations in mysql -
Allow to create mutilple model from foreign key in one view (with generic createview)
With django, I'm looking for a way to create easily a model which point to another models using Foreign Key in only one view using the generic create view. with an example, it should be easier to understant.. models.py # models.py from django.contrib.auth.models import User class Group(models.Model): name = models.CharField( _("Group name"), max_length=128, blank=False, null=False) comment = models.TextField(max_length=512, blank=False, null=False) def get_absolute_url(self): return reverse('group_detail', kwargs={'pk': self.pk}) def __str__(self): return _("%(name)s Group") % {'name': self.name} class UserAcl(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) group = models.ForeignKey(Group, blank=True, null=True, on_delete=models.SET_NULL) comment = models.CharField( _("comment"), max_length=128, blank=False, null=False) views.py enter code here # views.py class SettingsView(LoginRequiredMixin, UserPassesTestMixin, generic.ListView): model = UserAcl template_name = 'my_app/settings.html' When I display that view, I would like to access to all fields from User django class, all fields from Group class and of course all fields from UserAcl class. So 3 objects will be created : - User - Group - and finally the UserAcl. Whereas currently, only 3 fields are visible (those from UserAcl with the choice of User/group already in DB. Then when I post it, 3 object are saved ( User db (django), Group and UserAcl) How can I do that? since, didn't find it. Thx -
Optional pk argument for CREATE in Django's DRF ModelViewSet
I have a regular ModelViewSet for one of my models, but I want to have the option to specify a specific PK to create a new instance. E.g. if I would post: { "name": "Name" } It would get a random pk. But if I posted: { "id": "123", "name": "Name" } I want it to have the specified pk (id). Similar to this person, what I did is adding the id field to my ModelSerializer like this: class ConversationSerializer(serializers.ModelSerializer): id = serializers.CharField() # Instead of serializer.ReadOnlyField() class Meta: model = Conversation fields = '__all__' While this works for the create method, it causes issues for the update and partial_update ones, where id is now a required argument as a query string parameter and in the request body like this (from the docs): update PUT /conversations/{id}/ Update existing conversation. Path Parameters The following parameters should be included in the URL path. Parameter Description id (required) A unique value identifying this conversation. Request Body The request body should be a "application/json" encoded object, containing the following items. Parameter Description id (required) access_token username password app_user_id name How can I fix this such that the id parameter is only optional for the … -
django reverse in formModel
In my views.py I have a class who take a (CreateView) and in the form_class take a Testform in forms.py The problem is when in my forms.py I use the def save(...) method, it save correctly the data but the is no way to reverse after that it say to me no matter what I try to return it says "No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model." ok, so I've tried everywhere to put this method but no way, it allways gives me this error -
I searched a lot. and unfortunately i am not able to fix it . from django.urls import path is not working
What is the probelm ?I am getting lot of stress with this code. MY CODE:::: from django.contrib import admin from django.urls import path from basicapp import views urlpatterns = [ path('',views.index,name='index'), path('admin/', admin.site.urls), path('formpage/',views.form_name_view,name='form_name'), ] PROBLEM///ERROR:::: from django.urls import path ImportError: cannot import name path -
Django form with IntegrityError exception
I would like to get your help in order to use except IntegrityError in my formset. I have my model file : class Document(models.Model): code = models.CharField(max_length=25, verbose_name=_('code'), unique=True, null=False, blank=False, default='') language = models.CharField(max_length=2, verbose_name=_('language'), choices=LANGUAGE_CHOICES) format = models.CharField(max_length=10, verbose_name=_('format'), choices=FORMAT_CHOICES) title = models.CharField(max_length=512, verbose_name=_('title')) publication = models.ForeignKey(Publication, verbose_name=_('publication title'), related_name='documents') upload = models.FileField(upload_to='media/', validators=[validate_file_extension], verbose_name=_('document file'), ) class Meta: verbose_name = _('document') verbose_name_plural = _('documents') def save(self, *args, **kwargs): self.code = f"{self.publication.pub_id}-{self.language.upper()}-{self.format.upper()}" super(Document, self).save(*args, **kwargs) def __str__(self): return f"{self.title}" As you can see, the code field depends from data filled by user with the associated form. Each code field has to be unique. I have a formset : class DocumentForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(DocumentForm, self).__init__(*args, **kwargs) for key in self.fields: self.fields[key].required = True class Meta: model = Document fields = ['publication', 'language', 'format', 'title', 'upload'] DocumentFormSet = inlineformset_factory(Publication, Document, form=DocumentForm, extra=1, max_num=4, can_delete=True) And I have a views.py file with an except IntegrityError if user fills different form in formset with same value. Because it will create the same code ang user will get an error. class PublicationCreateView(CreateView): model = Publication template_name = 'publication_form.html' def get_context_data(self, **kwargs): context = super(PublicationCreateView, self).get_context_data(**kwargs) document_queryset = Document.objects.all() context['DocumentFormSets'] = DocumentFormSet(self.request.POST … -
Django 1.8 sqldiff for all apps ends in JSONField error
on a Django 1.8 project I´d like to sqldiff all tables in postgres. Running ./manage.py sqldiff -ae Ends in Traceback (most recent call last): File "./manage.py", line 31, in <module> execute_from_command_line(sys.argv) File "/home/vagrant/.venv/my_project/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/home/vagrant/.venv/my_project/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 346, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/vagrant/.venv/my_project/local/lib/python2.7/site-packages/django_extensions/management/commands/sqldiff.py", line 1085, in run_from_argv super(Command, self).run_from_argv(argv) File "/home/vagrant/.venv/my_project/local/lib/python2.7/site-packages/django/core/management/base.py", line 394, in run_from_argv self.execute(*args, **cmd_options) File "/home/vagrant/.venv/my_project/local/lib/python2.7/site-packages/django_extensions/management/commands/sqldiff.py", line 1072, in execute super(Command, self).execute(*args, **options) File "/home/vagrant/.venv/my_project/local/lib/python2.7/site-packages/django/core/management/base.py", line 445, in execute output = self.handle(*args, **options) File "/home/vagrant/.venv/my_project/local/lib/python2.7/site-packages/django_extensions/management/utils.py", line 59, in inner ret = func(self, *args, **kwargs) File "/home/vagrant/.venv/my_project/local/lib/python2.7/site-packages/django_extensions/management/commands/sqldiff.py", line 1065, in handle sqldiff_instance.find_differences() File "/home/vagrant/.venv/my_project/local/lib/python2.7/site-packages/django_extensions/management/commands/sqldiff.py", line 519, in find_differences self.find_field_type_differ(meta, table_description, table_name) File "/home/vagrant/.venv/my_project/local/lib/python2.7/site-packages/django_extensions/management/commands/sqldiff.py", line 405, in find_field_type_differ db_type = self.get_field_db_type(description, field, table_name) File "/home/vagrant/.venv/my_project/local/lib/python2.7/site-packages/django_extensions/management/commands/sqldiff.py", line 905, in get_field_db_type db_type = super(PostgresqlSQLDiff, self).get_field_db_type(description, field, table_name) File "/home/vagrant/.venv/my_project/local/lib/python2.7/site-packages/django_extensions/management/commands/sqldiff.py", line 277, in get_field_db_type field_class = self.get_field_class(reverse_type) File "/home/vagrant/.venv/my_project/local/lib/python2.7/site-packages/django_extensions/management/commands/sqldiff.py", line 295, in get_field_class return getattr(module, package_name) AttributeError: 'module' object has no attribute 'JSONField' regarding json this is what pip freeze tells me: anyjson==0.3.3 django-jsonfield==1.0.1 django-jsonfield-compat==0.4.4 jsonfield==2.0.2 simplejson==3.13.2 xmljson==0.1.9 How can I check where this JSONField error comes from? -
Django send an email on post_save with templates
I'm attempting to send an email our admin when new data is submitted to our website from the users. We are using a Django for the backend and Vue for the front end, even though that probably doesn't matter. Here is the code: @receiver(post_save) def send_update(sender, created, **kwargs): if created: data=kwargs['instance'] try: if data.admin_approved == False: print("point 1 reached") name = data.submitted_by_name body = data.body content_type = str(sender).split(".")[2][:-2] print("point 2 reached") link = "https://link_to_website.com" + content_type.lower() subject = "New " + content_type + " submitted" print("point 3 reached") from_email = "NoReply@web_site.com" to_email = "my_email@address.com" print("pre-html point reached") html_message = get_template('./email/template.html') text_message = get_template('./email/textplate.txt') data = { 'user_name': name, 'submission': data.body, 'type': content_type, 'link': link, 'body': body } content_text = text_message.render(data) content_html = html_message.render(data) print("ready to send email!") msg = EmailMultiAlternatives(subject, content_text, from_email, [to_email]) msg.attach_alternative(content_html, "text/html") msg.send() except: print("Data was not submitted by an non-admin user.") The try/except is included so that data that is submitted directly through the django admin page does not trigger the email function. the function works up until "pre-html point reached", I'm guessing the issue is somewhere within the msg and msg.send() but I am not receiving any error functions. Thanks for the help! -
Is there a way to remove links in HTML if a condition is not met?
I want to remove "a href" if a certain condition is met. In my case, when the word "None" appears, i do not want it to have a link. html: {% for item in responses %} <tr> <td style="border: 1px solid"><div style="height: 200px;overflow-y:auto;overflow-x:hidden"><a href="/media/{{ item.Document.Filename }}">{{ item.Document.Document_name }}</a></div></td> </tr> {% endfor %} So if {{ item.Document.Document_name }} == "None", i do not want it to have hyperlink -
Need help configuring apache .conf file
I want to deploy my django app on a Apache 2.4 server. The same server will host static files. The thing is that this server hosts other php based web sites. In ortder for all this to work I just need to install mod_wsgi and configure apache's .conf file related to this web site, is that right? After reading few articles I came up with this config, assuming that the web site will be in the var/www/ folder : <VirtualHost *:80> ServerName example.com # Alias /events /var/www/events/html ServerAdmin webmaster@localhost DocumentRoot /var/www/example Alias /media/ /var/www/example/media/ Alias /static/ /var/www/example/static/ <Directory /var/www/example/static> Order deny,allow Require all granted </Directory> <Directory /path/to/example/media> Order deny,allow Require all granted </Directory> WSGIScriptAlias / /var/www/example/events_promgruz/wsgi.py WSGIDaemonProcess example.com python-path=/var/www/example:/opt/envs/lib/python3.6/site-packages WSGIProcessGroup example.com <Directory /path/to/example/example> <Files wsgi.py> Order allow,deny Require all granted </Files> </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined What would you suggested to change or add to config? Is there some other steps to ensure that both django and php apps will work?