Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use django-cities to auto-populate custom user location field with cities based on user's ISP TLD?
I am using django 2.0.8 and Python 3.5 along with the latest version of django-cities. I have a custom user, with a location field. I want to use django-cities to present the user with a list of cities (based on the IP address). This is part of my code below: foo/models.py from django.db import models from django.contrib.auth.models import AbstractUser, UserManager from cities.models import Country, City # Create your models here. class MyUserManager(UserManager): pass class MyUser(AbstractUser): objects = MyUserManager() location = models.ForeignKey(City, on_delete=models.PROTECT) foo/utils.py def get_domain_tld(request): domain = request.META['HTTP_HOST'] return domain.split('.')[-1] foo/forms.py from django.forms import ModelForm from .models import MyUser from cities import Country, City # Create the form class. class MyUserForm(ModelForm): class Meta: model = MyUser # pseudo code follows below user_tld = get_domain_tld(request) # form should not be dealing with request obj! identified_country = Country.objects.get(tld=user_tld) cities = City.object.filter(country__name=identified_country.name) How do I modify the form class to populate a list based on the TLD? -
Need help decoding a Traceback for: cannot cast type integer to integer[]
I am trying to run a migration to allow some of my ArrayFields to be set to null. However, I am getting this confusing message: django.db.utils.ProgrammingError: cannot cast type integer to integer[] The 'schedule' column is empty in the actual database and I can't find the offending file in the traceback: Running migrations: Applying Events.0074_auto_20180829_2058...Traceback (most recent call last): File "/Users/adamstarrh/envs/otherlane/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: cannot cast type integer to integer[] The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Users/adamstarrh/envs/otherlane/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/adamstarrh/envs/otherlane/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/adamstarrh/envs/otherlane/lib/python3.7/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/Users/adamstarrh/envs/otherlane/lib/python3.7/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/Users/adamstarrh/envs/otherlane/lib/python3.7/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/Users/adamstarrh/envs/otherlane/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 203, in handle fake_initial=fake_initial, File "/Users/adamstarrh/envs/otherlane/lib/python3.7/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/Users/adamstarrh/envs/otherlane/lib/python3.7/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/Users/adamstarrh/envs/otherlane/lib/python3.7/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/Users/adamstarrh/envs/otherlane/lib/python3.7/site-packages/django/db/migrations/migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/Users/adamstarrh/envs/otherlane/lib/python3.7/site-packages/django/db/migrations/operations/fields.py", line 216, in database_forwards schema_editor.alter_field(from_model, from_field, … -
Async Django rest framework Database storage
Let me start by saying that I noticed that what seems to be the most popular answer for long async jobs is to use celery or the equivalent. I do not want you to question why I refuse to do this in this context. I want you to accept that I did my homeworks and I strongly think that in my case, something akin to a fork within django is the best approach. I have to convert a large file to multiple database objects in my ORM django models. I currently have a rabbitmq client server setup that recieves the large file, convert to json payloads and sends http request to POST those broken down json objects into the database. This works very very poorly for many reasons: it hammers the http API with a bunch of requests that are way more inefficient than simply converting file to json -> serializing internally. it makes dev env setup really messy and makes testing needlessly complicated. it requires a ton of lines of codes compared to what a forked within django code would look like. I am now running into rabbitmq configurations issues which further suggest this is the wrong approach. How … -
Beginner - using datatables server-side processing with django
I'm new to Django & web dev and looking for guidance on getting server-side processing working with my datatable. Basically, I have an external .db SQLite file with 500k records and I would like to display the records on a bootstrap datatable. In my views.py file, whenever they visit index.html, I make a query statement to fetch the records (not sure if that's inefficient but it's a small hobby website) groups = cursor.execute("""SELECT * FROM PlayerGroups""") return render(request, 'home/index.html', {'groups': groups}) # the issue since it returns 500k records which is too much for the client to handle. I understand I need to put something like this in "index.html": <script> $(document).ready(function(){ $('#example').dataTable( { "bProcessing": true, "bServerSide": true, "sAjaxSource": <confused about this part...> }); }); </script> I'm confused about making my own database API and linking the ajax source to my views/urls file. All of the guides I've looked online show server-side processing with models and stuff. I just have a external .db file I want to show on a datatable. Any guidance or help would mean a lot. -
I want to create a script which will able to send the email without using sender credential in django
I want to create a script which will able to send the email without using sender's credential in django. For example, when we try to send an email to someone then we require the sender's email and password. But i want to create a script which will able to send email without using sender's password. -
Django + Anymail + Mailgun - Email HTML renders without button and image
I am having an issue while trying to send an email containing html and an image, through mailgun, using the anymail library. This is my code: url_formulario = CLIENT_URL + str(token.key) email = EmailMultiAlternatives('Confirmación Vacante', to=emails) cid = attach_inline_image_file(email, '/var/www/static/icons/ba_logo.png') contexto = {'nombre_contacto': contacto.responsable_nombre, 'nombre_alumno': contacto.alumno_nombre, 'url_formulario': url_formulario, 'imagen':cid} mensaje = render_to_string('email.html', context=contexto) email.attach_alternative(mensaje, "text/html") email.track_clicks = True email.send() I have also tried doing it like this: url_formulario = CLIENT_URL + str(token.key) contexto = {'nombre_contacto': contacto.responsable_nombre, 'nombre_alumno': contacto.alumno_nombre, 'url_formulario': url_formulario} mensaje = render_to_string('email.html', context=contexto) content = strip_tags(mensaje) email = EmailMultiAlternatives('Confirmación Vacante', content,to=emails) email.attach_alternative(mensaje, "text/html") email.track_clicks = True email.send() Here are the two corresponding versions of the html file I am using: <html> <head> <title>Ingresa al formulario</title> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <!-- Bastrap CSS --> <link rel="stylesheet" href="/static/css/bastrap.css"> <style> .contenedor-general{ background:#e5e5e5; padding-top:3em; } .contenedor-general img{ padding-bottom:3em; } .contenido-mensaje{ background:white; margin-bottom:calc(43px + 6em); } .contenido-mensaje p{ font-family:"CHANEWEI", Helvetica, Arial, sans-serif; margin:7%; color:#717170; } .contenido-mensaje h1, .contenido-mensaje a{ margin: 0 7% 0 7%; } .contenido-mensaje h1{ padding-top:7%; color:#717170; } .contenido-mensaje a{ color:#333; } .btn-primary{ background-color:#fcda59 !important; color:#685723 !important; box-shadow:none !important; } .btn-primary:hover{ background-color:#fdd306 !important; border-color:#fdd306 !important; color:#685723 … -
Django scheduler showing blank page
i need to make a calendar for my website, i installed django-scheduler and the admin part work flawlessly, i can add calendar events and everything without problem, but i cannot make the calendar appear, the page load, so the template is found, and the urls are ok, but it loads blank, if i open devtool there is nothing in head/body. it is basically the code from this page https://github.com/llazzaro/django-scheduler/tree/develop/schedule settings.urls url(r'^calendar/', include('schedule.urls')), the app look is schedule feeds ical.py migrations locale models calendars.py event.py rules.py static templatetags scheduletags.py admin.py apps.py forms.py periods.py settings.py urls.py utils.py views.py widgets.py i believe the error is either in the views or in the models view.py class CalendarViewPermissionMixin(object): @classmethod def as_view(cls, **initkwargs): view = super(CalendarViewPermissionMixin, cls).as_view(**initkwargs) return check_calendar_permissions(view) class EventEditPermissionMixin(object): @classmethod def as_view(cls, **initkwargs): view = super(EventEditPermissionMixin, cls).as_view(**initkwargs) return check_event_permissions(view) class OccurrenceEditPermissionMixin(object): @classmethod def as_view(cls, **initkwargs): view = super(OccurrenceEditPermissionMixin, cls).as_view(**initkwargs) return check_occurrence_permissions(view) class CancelButtonMixin(object): def post(self, request, *args, **kwargs): next_url = kwargs.get('next') self.success_url = get_next_url(request, next_url) if "cancel" in request.POST: return HttpResponseRedirect(self.success_url) else: return super(CancelButtonMixin, self).post(request, *args, **kwargs) class CalendarMixin(CalendarViewPermissionMixin): model = Calendar slug_url_kwarg = 'calendar_slug' class CalendarView(CalendarMixin, DetailView): template_name = 'schedule/calendar.html' class FullCalendarView(CalendarMixin, DetailView): template_name = "schedule/fullcalendar.html" def get_context_data(self, **kwargs): context = super(FullCalendarView, self).get_context_data() … -
Django add Count annotation to a prefetch related query that is filtered
I'm using Django version 1.11 and I'm trying to execute the following query. queryset = Series.objects.prefetch_related( Prefetch( 'issues',queryset=Issue.objects.filter(hide=False) ) ) .filter(hide=False, issues__hide=False) .annotate('issue_count=Count('issues') ) The query runs perfectly fine the issue is that the annotated issue_count value is not correct. Instead of it reading back the count of the prefetch queryset it is just reading back the entire related issues property. Any suggestions?? -
Seeking advice for making social network like Medium (got lost in many techstacks and frameworks out there)
I am one of those aspiring ambitious youngsters wondering which tech stack to choose for developing a simple social network for sharing ideas (with the same purpose as Medium or alikes but in "Farsi"). I got my head busy with Lynda Learning Paths for becoming a web developer... took some courses in JS, CSS and HTML and didn't finish any of those yet. For the back-end, I have faced a not-so-easy problem which is, which language/framework/tool to choose for Rapid Development ease of coding and deployment as I'm the only member of the team and have to build both front- and back-end. Least learning over-head as I need to quickly bring something online to test the product and not waist my time and energy finding that no market exists for this product. I searched every where that I could, and at the very first I put the W/LAMP stack aside as I felt that PHP and MySQL are a bit old-school. Then read about node's "Exquisite Speed" and "Website Integrity" as both Front and back-end are built upon a same foundation. So I went on with the conventional JS frameworks for this project but didn't find that to be too … -
Django 1.11 - CreateView - invalid form raises error for nonexistent object attribute
Django 1.11, using generic class based views. When submitting an invalid form then the call super(CreateSupport, self).get_context_data(**kwargs) raises AttributeError: 'CreateSupport' object has no attribute 'object'. Expecting to show validation errors on form instead. View/Create when form is valid works alright. This is the class: class CreateSupport(IsAdminMixin, CreateView): model = Support form_class = SupportForm template_name = 'admin/support/form.html' success_url = reverse_lazy('admin-supports') def get_context_data(self, **kwargs): context = super(CreateSupport, self).get_context_data(**kwargs) if hasattr(self, 'object'): context['images_form'] = SupportForm.ProductImageFormSet( instance=self.object) if "validated_images_form" not in kwargs else kwargs["validated_images_form"] # filter the colour and size options for current vendor curr_vend = Vendor.objects.get(id=self.kwargs['vendorid']) context['colours'] = Colour.objects.filter(vendor=curr_vend) context['sizes'] = Size.objects.filter(vendor=curr_vend) return context def form_valid(self, support_form): if support_form.is_valid(): redirect = super(CreateSupport, self).form_valid(support_form) else: validated_forms_context = self.get_context_data(form=support_form) redirect = self.render_to_response(validated_forms_context) return redirect def post(self, request, *args, **kwargs): support_form = SupportForm(data=request.POST) return self.form_valid(support_form) I could not find any solution to this so far other than this old post using self.get_object() method that obviously would not work since the object has not yet been created. -
Maintaining a Read-Only Database in Django using Python Script
I have a python script which downloads data from an API source and transforms it in to a a list of dictionaries that I save as a JSON file. Separately, I have a Django project that uses this data to serve the data in a web page. I am currently using the default SQLite DB but plan on using Postgresql in production. The data is updated frequently, and so the script needs to download the new data on a daily basis and update the data being used by the Djano project's database. The issue is I can make the Django project "work" with dummy, sample data; and the script works independently of Django. How do I integrate this downloading script to work with Django and "push" new records and updates to the Django DB using the python script? Users of the Django project will only read the data and not write / update the data otherwise. I have reviewed a variety of tutorials such as the Django polls app but am lost on how to marry these two pieces together. Is this a case of using fixtures over and over against to reload data into the DB? It appears that … -
Django "view within a view"
I'm having difficulty understanding how Django allows for "modularized" views. This might not be out-of-the box behavior but I'll describe what I'm looking for... Suppose I have a view (think a "tab" on a web page menu) and I want for one of these tabs to have some one-off content. I'd like to be able to have a single HTML element contain content based upon completely different data. The view that's in use is determined by the URL. If the content of the "tab" (and therefor the view) is determined by /tabs/<tab_name>, how can I have just one tab contain an element, say a <div>, that gets its data from somewhere else. I am familiar with and understand the idea of including templates within templates. I could have a bit of template code that says "if this tab, then include this template using some data", but that data would have to be included (even if an empty object) in every tab. That seems ugly to me. Another way of asking: suppose I want to create an app that shows the local weather. If I provide a view and map it to a URL, I would only be able to display … -
Django - How would I apply CSS for a radio model formset?
I want to customize a radio form in Django, but because of the way that the formset is rendered by Django, I'm unable to customize it properly. The CSS rules that I've been using assume that the <input> tag and the <label> tag are next to each other, but the way that Django renders the form has the <input> tag inside of the <label> tag. These are the CSS rules that I'm applying, with the HTML [type="radio"]:checked + label, [type="radio"]:not(:checked) + label { cursor: pointer; } input[type=checkbox], input[type=radio] { display: none; } input[type=checkbox] + label:before { font-family: "Font Awesome 5 Free"; display: inline-block; content: "\f0c8"; /* Unicode for Font Awesome icons */ } input[type=radio] + label:before { font-family: "Font Awesome 5 Free"; margin-right: 10px; display: inline-block; content: "\f0c8"; /* Unicode for Font Awesome icons */ } input[type=checkbox]:checked + label:before, input[type=radio]:checked + label:before { content: "\f14a"; } <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous"> <form action="#"> <p> <input type="radio" id="test1" name="radio-group" checked> <label for="test1">Yes</label> </p> <p> <input type="radio" id="test2" name="radio-group"> <label for="test2">No</label> </p> </form> While the HTML that's generated by Django is: <ul id="set-0-field"> <li> <label for="id_model_set-0-field_0" style="color: black;"> <input value="1" required="required" id="id_model_set-0-field_0" name="model_set-0-field_0" type="radio"> Yes </label> </li> <li> <label for="id_model_set-0-field_1" style="color: black;"> … -
Interface to allow users to edit their Django model entries
The admin interface for editing (adding, deleting, changing) entries in the database is great. I am working on a system, based on HTML forms, to allow users to edit information relevant to them in the database. This will take a lot of work, and look less than professional. Is there a standard way to allow a logged in user to use an administration-interface-like page to edit their (and only their) entries in a DB/model? -
Writing my own custom back-end in Django
I am trying to build an application which consumes a third party API. I want to implement OAuth2 in my application using that API. Now, I am able to receive the authorization token, followed by an access token and refresh token. But, I am lost after this! How do I used those tokens to authenticate those users in my application? I could not find any tutorial regarding this. Please help me here. In a way, I want to know how python-social-auth implements the authentication back-end. That would also help, I guess. Thank you! -
Sort django signal's receivers
Django calls receiver methods in its own way. Is there any way that we can sort the receivers of Django signal? I didn't find anything related to it in official Django documentation. -
Django: image not saved when using CreateView with a HTML template
To wrap some text around one of my CreatView classes I use a HTML template to wrap the form. However, when using this template everything works as expected except that the image passed to the ImageField of the form is not saved. Commenting out the the line where the template of the CreateView is set solves the problem. But I would like to use the template to have the option to show more on the page than just the form. How does the logic of the form change when wrapping it into a template? views.py class PieceInstanceCreate(LoginRequiredMixin, CreateView): model = PieceInstance fields = ['version', 'piece_image', 'status'] # commenting out the below line makes the form save the image template_name = 'pieceinstance_create.html' def form_valid(self, form): form.instance.piece = Piece.objects.get(id=self.kwargs['pk']) return super(PieceInstanceCreate, self).form_valid(form) def get_success_url(self): return reverse_lazy('piece-detail', kwargs={'pk': self.kwargs['pk']}) pieceinstance_create.html {% extends "base_generic.html" %} {% block content %} <h1>Add a Version</h1> <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"> </form> {% endblock %} -
Optimal way to handle multiple link from url and views
I am actually creating the general structure of a "web-page" (it is just for training). In my main.html I have some link to other pages <div Id="topnav"> <a class="active" href="{% url 'Home' %}">Home</a> <a href="{% url 'News' %}">News</a> <a href="{% url 'Contact' %}">Contact</a> <a href="{% url 'About' %}">About</a> </div> My question is: Is there a way to automatize the handelling of all these links when creating a view and the urlpattern? My url.py is like this urlpatterns = [ path('admin/', admin.site.urls), path('main/', mainPage), path('main/home', home, name='Home'), path('main/news', news, name='News'), path('main/contact', contact, name='Contact'), path('main/about', about, name='About'), ] For the moment is ok, but if one have more links it become quickly annoying. Is there a better way to handle this kind of situation? -
The parameter redirect_uri is required while using facebook login in my django application?
I am using facebook auth login in my Django application. I create an app in from https://developers.facebook.com In the basic facebook login app, I add my domain name in Valid OAuth Redirect URIs and also add the domain name in Redirect URI to Check.I set all the Client OAuth Settings to YES. I have also addes SOCIAL_AUTH_FACEBOOK_KEY = ********** # App ID SOCIAL_AUTH_FACEBOOK_SECRET =************* #App secret in my settings.py file and use this url for facebook logon button <p><a href="{% url 'social:begin' 'facebook' %}">Continue With Facebook</a> </p> However when I tried to log in from my facebook account then I got the following error: The parameter redirect_uri is required For reference I follow this blog for facebook login https://simpleisbetterthancomplex.com/tutorial/2016/10/24/how-to-add-social-login-to-django.html Please help me in figure out my issue. -
django-hosts: self.request.user on subdomain returns AnonymousUser
in my Project I use django-hosts to develope downloads at downloads.foo.bar instead of foo.bar/downloads. Getting context data etc works all fine, but I want to have downloads restricted to authenticated users. The view which gets called is the IndexDownloadView. First I tried the LoginRequiredMixin. With this I got always redirected to the login page when calling any link of the downloads-subdomain. The login is managed via an users-app within my project and main-app host. To find out whats wrong I took the Mixin away and print(self.request.user) on my subdomain-cbv which returns AnonymousUser. Doing this in my main-app (no subdomain) it returns the logged in user. One thing I think is weird: I extend the subdomain template from a base.html. The base.html has a Button in the menu with a link/text to login or logout depending on {% if request.user.is authenticated %} in the template. This snippet seems to recognize the authenticated user because the logic shows the login-page if not authenticated vice verse. The block with the main content doesn't. hosts.py from django_hosts import patterns, host from django.conf import settings host_patterns = patterns('', host(r'', settings.ROOT_URLCONF, name='main'), host(r'www', settings.ROOT_URLCONF, name='www'), host(r'downloads', 'downloads.urls', name='downloads'), ) base.html #Menu-stuff {% if user.is_authenticated %} <form … -
Django admin list_filter - dropdown widget
I can change list_filter of related object to dropdown. The problem is when I want to filter on related objects of related object: class Match(Model): team = models.ForeignKey('Team'...) class Team(Model): country = models.ForeignKey('Country'...) When I want to filter Match objects by Team, I do: list_filter = ['team__country'] To dropdown this filter, I use https://github.com/mrts/django-admin-list-filter-dropdown: list_filter[('team',RelatedDropdownFilter)] When I want to filter Match objects by Country of their Team: list_filter = ['team__country'] But when I want to make dropdown from this filter, it doesn't work: list_filter = [('team__country',RelatedDropdownFilter)] It looks the same as there were not RelatedDropdownFilter specified. RelatedDropdownFilter class RelatedDropdownFilter(RelatedFieldListFilter): template = 'django_admin_listfilter_dropdown/dropdown_filter.html' Template {% load i18n %} <script type="text/javascript">var go_from_select = function(opt) { window.location = window.location.pathname + opt };</script> <h3>{% blocktrans with title as filter_title %} By {{ filter_title }} {% endblocktrans %}</h3> <ul class="admin-filter-{{ title|cut:' ' }}"> {% if choices|slice:"4:" %} <li> <select style="width: 95%;" onchange="go_from_select(this.options[this.selectedIndex].value)"> {% for choice in choices %} <option{% if choice.selected %} selected="selected"{% endif %} value="{{ choice.query_string|iriencode }}">{{ choice.display }}</option> {% endfor %} </select> </li> {% else %} {% for choice in choices %} <li{% if choice.selected %} class="selected"{% endif %}> <a href="{{ choice.query_string|iriencode }}">{{ choice.display }}</a></li> {% endfor %} {% endif %} </ul> Do … -
How to configure settings.py for mongoDB connection in Django we application
I am getting following error : django.core.exceptions.ImproperlyConfigured: 'django_mongodb_engine' isn't an available database backend. And the official documentation of django says.... no mongodb Try using 'django.db.backends.XXX', where XXX is one of: u'mysql', u'oracle', u'postgresql_psycopg2', u'sqlite3' -
Unknown errors when running Django project
I am having trouble running a Django app called "cs3" cloned from Github Here is a picture of how my directory is organized. When I write the python3 manage.py runserver command in terminal, I get the following code. Moreover, the line under it no longer starts with (shell) Joshs-MacBook-Pro-2:, it is just blank. How do I fix these errors and run this project on my browser? (shell) Joshs-MacBook-Pro-2:cs3 joshlurie$ python3 manage.py runserver Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x110ec30d0> Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/base/base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/postgresql/base.py", line 174, in get_new_connection connection = Database.connect(**conn_params) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/psycopg2/__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: fe_sendauth: no password supplied The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 379, in check include_deployment_checks=include_deployment_checks, File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 366, in _run_checks return checks.run_checks(**kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/checks/registry.py", line 71, in run_checks new_errors = check(app_configs=app_configs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver … -
Model not defined with ManyToManyField
I have a problem to make a migration of a model for Django 2.1. I have created this two class models: class PostModel(models.Model): post_title = models.CharField(max_length=70) post_short_description = models.CharField(max_length=200) post_contents = models.TextField() post_publishing_date = models.DateTimeField(auto_now=False, auto_now_add=True) post_keyconcept = models.ManyToManyField(KeyConceptModel) post_slug = models.SlugField(unique="True") post_highlighted = models.BooleanField(default=False) def __str__(self): return self.post_title class KeyConceptModel(models.Model): concept_text = models.CharField(max_length=50) def __str__(self): return self.concept_text When I try to start makemigrations, the console return: NameError: name 'KeyConceptModel' is not defined The error point to the line of post_keyconcept. If I comment all of KeyConceptModel and the line post_keyconcept, the migrations are successfull. I don't know what is wrong, I'm new into the Django and Python world... -
Django; templatetags doesn't work
I was trying to use templatetags but it doesn't work. my tag is like this register = template.Library() @register.simple_tag(takes_context=True) def is_upvoted(context): """return if the user already upvoted or not""" request = context['request'] entry = context['entry'] try: Entry.objects.get( id=entry.id, upvoted=request.user, ) return True except: return False html is like this {% load app_name_tags %} {% if is_upvoted %} <img src=""> {% else %} <img src=""><!-- replace image --> {% endif %} bascically I used it to tell if the user already upvoted or not and I want to change the image depeding on this. But the image doesn't change at all. what am I wrong with how to use templatetag? Also, I actually want to use templatetag inside loop like {% for entry in entries %} <!-- check if the user already upvoted to the entry or not --> In this case, how I can take argument in the templatetag?