Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django site works locally not remote - returns page not found for any url path
I inherited a django site project which I have managed to setup and run locally. However when I attempt to deploy the django site remotely I am getting the following message while testing: Page not found (404) Request Method: GET Request URL: http://x.y.z.a:8000/ Raised by: core.views.HomeView Here is the following relevant information: Ubuntu 18.x running a virtual env (python 3.7.0) The message received. Again, not that I am getting the site to work fine locally. Let's ignore for now all the standard site checks (the site is pre wsgi / gunicorn / nginx etc. integration), so for the purposes of this test I am simply running python manage.py runserver 0.0.0.0:8000 - for now . Also note that port 8000 is open from this server (otherwise I would not get the debug view at all) From the screen it is referring to core.views.HomeView . in the "core" folder there us urls.py, which looks like this. from what I can see, there is nothing out of the ordinary here. So tracing it further, I can go to views.py Again, don't see anything out of the ordinary here, and the site does run locally. The home html page that is being referred to … -
Django: how to transform `path` url to DRF `router` url?
In a Django 2.1.4 project I had a working path-based urlpattern for a DRF view (that has a dynamic serialization if it matters): path('content/<str:slug>/<str:model>', views.ContentViewSet.as_view(), name='content') Then I decided to change my view to the viewset and now need to update the urlpattern. I tried: router = DefaultRouter(trailing_slash=False) router.register( # 'content/<str:slug>/<str:model>', # this didn't work either r'^content/(?P<slug>[-\w]+)/(?P<model>[\w]+)/$', views.ContentViewSet, base_name='content' ) urlpatterns += router.urls But got this error: '"%s" is not a valid regular expression: %s' % (regex, e) django.core.exceptions.ImproperlyConfigured: "^^content/(?P<slug>[-\w]+)/(?P<model>[\w]+)\.(?P<format>[a-z0-9]+)/?\.(?P<format>[a-z0-9]+)/?$" is not a valid regular expression: redefinition of group name 'format' as group 4; was group 3 at position 86 How to configure my urlpattern for router? -
Extending User model with one to one field- how to set user instance in view
I am trying to extend the user model using a one to one relationship to a UserProfile model. I added some boolean fields and in the view I am trying to use those fields as permissions. Here is my model: class UserProfile(models.Model): user = models.OneToOneField(User) FirstName = models.CharField(max_length=25) LastName = models.CharField(max_length=25) ProximityAccess = models.BooleanField(default=True) NewProxAccess = models.BooleanField(default=False) def __unicode__(self): return self.user.username and here is the view I am trying to use: @login_required def NewProx(request): if UserProfile.NewProxAccess: if request.method == 'POST': form = ProxForm(request.POST) if form.is_valid(): ProxPart_instance = form.save(commit=True) ProxPart_instance.save() return HttpResponseRedirect('/proximity') else: form = ProxForm() return render(request, 'app/NewProx.html', {'form': form}) else: raise PermissionDenied I don't get any error messages but it does not work as intended. I was hoping that if the user profile had NewProxAccess set to False it would raise the PermissionDenied but it doesn't. I have the admin module wired up and I can select or deselect the checkbox for that field but it has no effect. If I comment out the rest I can get it to show the Permission Denied error so it has to be in the view (I think). I think I am missing a line the establishes the logged in user as … -
get_channel_layer() outside browser
I have an API and I would like to call events that would update via websocket messages, as required. Think of something like a live filesystem, where someone may add a file either in the interface or by API and anyone viewing that folder would be able to view the update file paths. Here is what I'm currently doing in the web views: channel_layer = get_channel_layer() data = { "file": entity_data, "instanceId": None, "user": self.user_id, "type": "DELETE_FILE" } async_to_sync(channel_layer.group_send)( 'folder_event_' + str(parent_entity_access.entity_id), { "type": "folder_event_broadcast", "data": data } ) How would I do the same thing outside of the web application -- i.e., "get the channel layer" ? -
Filtering OrganizationUser's by Organization in Django-Organizations
There is a relatively similar thread on this topic, but I can't seem to figure out how to translate it to my situation. I have a roster that I need to only display the organizationusers within the same organization of the viewer. I have a webapp that I am developing that is used to manage volunteers in an organization. I'm still new to backend development so I'm having trouble problem solving. This is the code for the table view using Django_Tables2 package: #tables.py class VolunteerTable(tables.Table): class Meta: model = OrganizationUser # views.py def VolunteerRoster(request): table = tables.VolunteerTable(OrganizationUser.objects.all()) return render(request, 'staff/roster.html', {'table': table}) I'm trying to figure out how to either convert the view to a class-based view so I can use the OrganizationMixin and the SingleTableView in Django_Tables2's documentation. I was thinking about something like this based on the other threads explanation class VolunteerRoster(SingleTableView, OrganizationMixin): table_class = VolunteerTable queryset = OrganizationUser.objects.all() template_name = "staff_roster.html" def get_queryset(self): return self.queryset.filter(organization=self.get_organization()) When I try this I get: "TypeError: init() takes 1 positional argument but 2 were given" As I said, I'm still new to django so I'm not really sure what to fix in this instance. -
Django - Get name of model object by iterating through class
I'm new to Python (and pretty inexperienced at programming in general), but I have an issue I can't for the life of me figure out. I'm trying to pre-populate a field in my database with the name of an instance from another model/class in my database. The model with the field I want to pre-populate is an "instance" of the model instance from which I'm trying to grab the name, and has a foreign key to that instance. Goal: 1) User selects the parent of the object by assigning the foreign key to the parent 2) A function grabs the name of the parent instance matching the foreign key the user selected. 3) the result from that function is used as the default value for the field. Here's the code: class Injury(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text='Unique ID for this particular injury') name = models.CharField(max_length=200, help_text='Enter an injury or complication (e.g. respiratory failure)') description = models.TextField(max_length=1000, blank=True, help_text='Describe the injury') time_to_onset = models.PositiveIntegerField(blank=True, validators=[MaxValueValidator(10000)], help_text='Enter expected time from trigger until injury/complication onset') findings = models.TextField(max_length=1000, blank=True, help_text='Enter the signs and symptoms of the injury or complication') vitals_trends = models.TextField(max_length=1000, blank=True, help_text='Enter the vitals changes due to the injury') class Meta: … -
What is the best practice in structuring templates in your Django project?
I know there's a lot of questions regarding best practices of how to structure an entire Django project but i cannot find a concrete explanation on how to structure templates for a Django project. Obviously, I've just started learning Python/Django and i'm quite confused why most of the tutorials/examples i found, the directory name under templates directory is always the same as the its applications directory name. For example: gazette/ __init__.py models.py views.py static/ ... templates/ gazette/ __base.html __l_single_col.html __l_right_sidebar.html __l_left_sidebar.html _article_full.html _article_summary.html _author_list.html _author_name.html _category_list.html _navigation.html _tag_list.html article_detail.html article_list.html author_list.html category_list.html tag_list.html this actually came from a blog: https://oncampus.oberlin.edu/webteam/2012/09/architecture-django-templates In the application structure above, the application gazette/ have templates/ directory under it. In turn, under templates/, there's a single directory called gazette/, which is the same name as the application where it resides. This folder then contains all the actual html template files. Question: Why can't we just directly put all the html template files under templates/ directory? I would understand the logic of the structure if there are several directories under templates but i never found a single example from any tutorials in YouTube or blogs. If you could explain the principle behind it and direct me to … -
Relationship field in Django
I have the following structure in my models.py document: class Player(Human): name = models.CharField(max_lenght=24) jersey_number = models.IntegerField() class Coach(Human): name = models.CharField(max_lenght=24) class Team(models.Model): name = models.CharField(max_length=24) players = models.SomethinToSomething(Player) coaches = models.SomethinToSomething(Coach) I would like in my admin section to create teams and inside each team add some players and some coaches, I want that a player is related only with the team where I created it, so if I'm in team A it has to be impossible for me see and adding player of other team. I tried OneToOne() but I can link only one player and only one coach to the team. I tried ManyToMany() but when I make the second team the players of the first team are shared with the first team. What should I use? -
Setting up Django with MySQL on macOS
I'm new to Django, and trying to setup a basic web-app connecting to MySQL on macOS. However, I can't seem to get mysqlclient to work on macOS. I'm running a virtual environment and the following versions: $ brew --version Homebrew 1.8.5 $ pip --version pip 18.1 $ python --version Python 3.7.1 $ mysql --version mysql Ver 8.0.12 for osx10.14 on x86_64 (Homebrew) When I try pip install mysqlclient (https://pypi.org/project/mysqlclient/) I get ld: library not found for -lssl clang: error: linker command failed with exit code 1 (use -v to see invocation) error: command 'gcc' failed with exit status 1 According to the documentation "You may need to install the Python and MySQL development headers and libraries like so:" $ brew install mysql-connector-c This gives another error: Error: Cannot install mysql-connector-c because conflicting formulae are installed. mysql: because both install MySQL client libraries Please `brew unlink mysql` before continuing. $ brew unlink mysql $ brew install mysql-connector-c ==> Pouring mysql-connector-c-6.1.11.mojave.bottle.tar.gz 🍺 /usr/local/Cellar/mysql-connector-c/6.1.11: 79 files, 15.3MB brew link mysql Error: Could not symlink bin/my_print_defaults Target /usr/local/bin/my_print_defaults is a symlink belonging to mysql-connector-c $ brew link --overwrite mysql Now I can start mysql from console, but when I update django, mysite settings.py to … -
PyCharm: No manage.py file specified in Settings->Django Support after refactoring project name
How to configure Pycharm to detect manage.py correctly? I've modified my project name perfectcushion to llama-stickers, using Pycharm IDE refactor -> rename. However, now I get this error: No manage.py file specified in Settings->Django Support when trying to runserver from Pycharm IDE. I also notice that the project is called: llama-stickers**[perfectcushion]**, why is there the old name of the project? Is there something I miss to refactor? settings.py """ Django settings for llama-stickers project. Generated by 'django-admin startproject' using Django 2.1.3. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '^_67&#r+(c+%pu&n+a%&dmxql^i^_$0f69)mnhf@)zq-rbxe9z' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'shop', 'search_app', 'cart', 'stripe', 'order', 'crispy_forms', ] 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', ] ROOT_URLCONF = 'llama-stickers.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates'), … -
Custom field Choices error in Django rest framework
I currently have a problem with creating a Choice field field in the Django Rest Framework. At first, looking for solutions in google, I found the best practices to apply the solution in my project. However, I came across problems in the service remaining from the application, bring it the way to present the field. Since I need to manipulate information through fixed options, I had to follow the methodology of even creating a specific serializer for this. Before using the ChoiceField field of the DRF, I am able to correctly choose the option but cannot demonstrate the value by getting the name of the variable in the response. My wish is that the value and not the name of the variable to be displayed. For this I created the following structure: My script, called choices.py # Model custom using ENUM concept from enum import Enum from rest_framework import serializers class ChoiceEnum(Enum): @classmethod def choices(cls): return tuple((x.name, x.value) for x in cls) #Serializer custom ChoicesField class ChoicesField(serializers.Field): def __init__(self, choices, **kwargs): self._choices = choices super(ChoicesField, self).__init__(**kwargs) def to_representation(self, obj): return self._choices[obj] def to_internal_value(self, data): return getattr(self._choices, data) My Model class Discount(models.Model): class DiscountTypes(ChoiceEnum): VALUE = 'value_absolute' PERC = 'percentual' employee … -
Django REST Framework -- Many2Many/Through
In general, I am confused about my serializers for the following models. Would someone be willing to look at this code and see if it makes sense/if something needs to be changed in order for my serializers to work properly? Here is the models.py: from django.db import models from django.contrib.auth.models import User class Course(models.Model): prefix = models.CharField(max_length=100) course_num = models.CharField(max_length=100) lecture_hours = models.CharField(max_length=20) lab_hours = models.CharField(max_length=20) credit_hours = models.CharField(max_length=20) date = models.DateField(auto_now=False, auto_now_add=False) previous_version = models.ForeignKey('self', on_delete=models.DO_NOTHING, blank=True, null=True) class Meta: ordering = ('prefix') class Term(models.Model): semester = models.CharField(max_length=100) year = models.CharField(max_length=100) name = models.CharField(max_length=200) courses = models.ManyToManyField(Course, through='Offering', related_name='terms') def termCourses(self): term_courses = self.courses.all() return term_courses class Offering(models.Model): term = models.ForeignKey(Term, on_delete = models.CASCADE) course = models.ForeignKey(Course, on_delete = models.CASCADE) instructor = models.ForeignKey(User, on_delete = models.CASCADE) class TermPermission(models.Model): creator = models.ForeignKey(User, on_delete = models.CASCADE) term = models.ForeignKey(Term, on_delete = models.CASCADE) Here is the serializers.py from django.contrib.auth.models import User, Group from .models import Course, Term, Offering from rest_framework import serializers class CourseSerializer(serializers.ModelSerializer) class Meta: model = Course fields = ('prefix,', 'course_num', 'lecture_hours', 'lab_hours', 'credit_hours', 'date', 'previous_version', 'terms' ) class TermSerializer(serializers.ModelSerializer) courses = OfferingSerializer(source='offering_set', many=True) class Meta: model = Term fields = ('semester,', 'year', 'name', 'courses', ) class OfferingSerializer(serializers.ModelSerializer) offering_term = … -
Fail to Import View from main Django project folder into app views.py
I have a problem to import a view from the main Django project views.py into my app's views.py. This is what happens: ImportError: cannot import name 'index' from 'ebdjango.views' (/Users/iamsuccessful/ebdjango/ebdjango/views.py) Inside dailytask/views.py (app folder) from ebdjango.views import index Inside ebdjango/views.py (main Django project folder) @login_required(login_url="/login") def index(request): user = request.user if user.userprofile.daily_task_done is False: return render(request, 'home.html') elif user.userprofile.daily_task_done is True: return task_done(request, pk=user.userprofile.daily_task) What do I need to do to import the view Index into the app views.py? -
Unable to extend Django 2.1 password reset template
I'm trying to extend the password reset form like so: <!-- templates/registration/password_reset_form.html --> {% extends registration/password_reset_form.html %} {% block content %} <h1> hello </h1> {% endblock %} As far as I can tell, this should take the template from /usr/local/lib/python3.7/site-packages/django/contrib/admin/templates/registration/password_reset_template.html (which exists, I checked) and replace the block content with the one at templates/registration/password_reset_form.html. But this isn't happening. In fact, there is no change, nor is there an error. What am I doing wrong? -
can you update a model instance without calling save( )?
I am working on a project that requires unique slugs. The slugs are dynamically created in a custom save() method using the objects name. class SlugMixin(models.Model): def save(self, *args, **kwargs): slug = striptags(self.name) self.slug = slugify(slug) super(SlugMixin, self).save(*args, **kwargs) class Meta: abstract = True name is not unique so it's possible to have multiples of the same slug. So the solution i was working with is appending the id of the instance to it's slug in a post_save. The problem here is by attempting to update the slug with the id. save() needs to be called again. def ensure_unique_slug(sender, instance, created, **kwargs): if created and Person.objects.filter(slug=instance.slug).count() > 1: instance.slug = instance.slug + '-{}'.format(instance.id) instance.save() rendering the update useless. is there anyway to update the slug without calling save() -
In Django, what is a good example of static files ending up in a reference loop?
Per the Django-1.11 upgrade notes re: python manage.py collectstatic "Testing needs to be done to make sure that - Static files do not end up in a reference loop - Static files are not chained too deep (might not resolve)" I've been trying to figure out a good example of the situation to which this is referring. A quick example would be appreciated, thanks. -
Django Rest Framework get a lookup field as a list of hyperlinks
I have a model Album and a model Photo, which references the first one through a FireignKey field. I want the ModelSerializer for model Album to return a list of hyperlinks to relate entries in model Photo through a lookup field, but I only get it to return a list of ids. These are my models: class Album(models.Model): name = models.CharField(max_length=200, verbose_name=_("Name")) description = models.TextField(null=True, blank=True, verbose_name=_("Description")) company = models.ForeignKey(Company, on_delete=models.PROTECT, related_name='albums', verbose_name=_("Company")) access_code = models.CharField(max_length=30, default=_create_access_code, verbose_name=_("Internal Use")) class Meta: verbose_name = _("Album") verbose_name_plural = _("Albums") def __str__(self): return "[{}] {} ({})".format(self.pk, self.name, self.company.id) class Photo(models.Model): name = models.CharField(max_length=100, null=True, blank=True, verbose_name=_("Name")) album = models.ForeignKey(Album, on_delete=models.PROTECT, related_name='photos', verbose_name=_("Album")) photo = models.ImageField(verbose_name=_("Photo")) class Meta: verbose_name = _("Photo") verbose_name_plural =_("Photos") def __str__(self): return "[{}] {}".format(self.pk, self.name) And this is my serializer: class AlbumSerializer(serializers.ModelSerializer): class Meta: model = proxies.AlbumProxy fields = ('id', 'name', 'description', 'company', 'access_code', 'photos') I want the field photos to return a list of hyperlinks, but I get a list of ids: "id": 1, "name": "Navidad 2018", "description": "La primera", "company": 1, "access_code": "xxxxxxxxxx", "photos": [ 11, 10, 7, 6 ] -
Django ModelForm Not Saving to DB
I'm new to Django and having a hard time figuring out how to get a model form to save to my db. I've been following some tutorials/books and spending a lot of time on SO and I just can't figure this piece out. The book examples i'm following is creating an IMDB type website where a user can vote movie quality (changed to games for my example). python v. 3.6.7, django v. 2.1.3, postgres v. 2.2.2 Here is the model i'm trying to store and the associated manager class VoteManager(models.Manager): def get_vote_or_unsaved_blank_vote(self, game, user): try: vote = Vote.objects.get(game=game, user=user) return vote except self.model.DoesNotExist: vote = Vote(game=game, user=user) return vote class Vote(models.Model): objects = VoteManager() value = models.FloatField() user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) game = models.ForeignKey(Game, on_delete=models.CASCADE,) voted_on = models.DateTimeField(auto_now=True) class Meta: unique_together = ('user', 'game') Now the model form I am trying using to try and store this class VoteForm(forms.ModelForm): user = forms.ModelChoiceField(widget=forms.HiddenInput, queryset=get_user_model().objects.all(), disabled=True) game = forms.ModelChoiceField(widget=forms.HiddenInput, queryset=Game.objects.all(), disabled=True) value = forms.FloatField() class Meta: model = Vote fields = ('user', 'game', 'value') Template i'm using to display this information. {% block main %} <h1>{{ object }}</h1> <p class="lead"> {{ object.summary }} </p> {% endblock %} {% block sidebar %} {# … -
Django Autocomplete-light dependant visibility
I have 2 autocomplete dropdown list using autocomplete-light I want that the visibility of the second dropdownlist (cars) be dependent on the value of the first dropdownlist(raste) but i dont know how can i find their id ? Forms.py : class StocksForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(StocksForm, self).__init__(*args, **kwargs) for field_name, field in self.fields.items(): field.widget.attrs['class'] = 'form-control' field.widget.attrs['style']= 'width:60%' class Meta(): model=Stocks fields=('user','raste','car','stname','mark','description','pic','price') widgets = { 'raste': autocomplete.Select2(url='BallbearingSite:stock_autocomplete'), 'car': autocomplete.Select2(url='BallbearingSite:car_autocomplete'), } Html : <form enctype="multipart/form-data" method="post" > {% csrf_token %} {{ stocks_form.as_p }} <input id="savestocks" type="submit" name="" value="ثبت"> <input type="text" name="search" id="txtSearch" onkeyup="searchOpen()" /> <input type="text" id="id_input"> <div> <input type="text" id="contact_name_search_input" name="contact_name_search" /> </div> <div class="ui-widget"> <label for="places">Places: </label> <input id="places"> </div> </form> and these are the javascript codes which i wrote but it doesnt work ! <script> $(document).ready(function() { $('#select2-id_raste-container').change(function() { var selectedValue = $(this).val(); if(selectedValue === 'abc') { $('#select2-id_car-container').closest('span').hide(); } else if (selectedValue === 'bcd') { $('#select2-id_car-container').closest('span').show(); } }); }); </script> the html codes which are in the firefox consule : <label for="id_raste">Raste:</label> <select class="form-control select2-hidden-accessible" data-autocomplete-light-function="select2" data-autocomplete-light-url="/stock_autocomplete/" id="id_raste" name="raste" style="width:60%" tabindex="-1" aria-hidden="true"> </select> <span class="select2 select2-container select2-container--default" dir="ltr" style="width: 60%;"> <span class="selection"> <span class="select2-selection select2-selection--single" role="combobox" aria-haspopup="true" aria-expanded="false" tabindex="0" aria-labelledby="select2-id_raste-container"> <span class="select2-selection__rendered" id="select2-id_raste-container"><span class="select2-selection__placeholder"> </span> </span> <span … -
Problem with ERR_TOO_MANY_REDIRECTS django 2.1
I started to create login module in django. Login module is ok but I have problem with logout. When i click Logout - we see "error -ERR_TOO_MANY_REDIRECTS" Probably something in this file is incorect: account/urls.py from django.conf.urls import url from django.urls import path from django.contrib.auth import views as auth_views from . import views app_name = 'account' urlpatterns = [ path('', auth_views.LoginView.as_view(template_name='account/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='registration/logout.html'), name='logout'), path('logout-then-login/', auth_views.logout_then_login, name='logout_then_login'), path('dashboard/', views.dashboard, name='dashboard'), -
How to POST data to a Django Form that contains checkboxes
I have a problem when I am testing my registration form in Django. I am trying to make a POST request but I cannot select a checkbox field. self.response = self.client.post(url, { 'username': 'testuser', 'password': 'testuserpassword', 'first_name': 'testtt', 'last_name': 'userrr', 'image': '', 'email': 'testuser@gmail.com', 'gender': 'M', 'dob': '10/10/1996', 'hobby': 'Fishing' }) This is my line of code. The problem is at Hobby. The registration page is made of two forms. A profile form and a hobby form. There is a many-to-many relationship between Profile and Hobby models. When I make the above POST request, I get this (Select a valid choice): Thank you in advance! -
How can get minute_step=15 using TimeField in Django?
I created a form with two time fields. I would like to get only 00mn 15mn 30mn and 45mn in my minutes widgets. Thank you Here is my form: class JobForm(forms.ModelForm): start = forms.TimeField(widget=forms.TimeInput(format='%H:%M')) end = forms.TimeField() class Meta: model = Job fields = ('start', 'end') here is my template: <div class="input-group clockpicker" data-placement="left" data-align="top" data-autoclose="true"> <form method="POST" class="post-form"> {% csrf_token %} <table class="table table-bordered table-fit" border="0" > {{ form }} </table> <button type="submit" class="save btn btn-default">OK</button> </form> </div> <script type="text/javascript"> $('#id_start').clockpicker({ donetext: 'OK'}); $('#id_end').clockpicker({donetext: 'OK'}); </script> -
It is possible to update db from web-page in Djano?
There is a django-site with models and db. It is possible to update/add to the db info from my models like a = Model() a.name = 'name' a.save() directly form site page, but not througth admin page? -
Django form action attribute is not working propely
I am working on app in django 1.11, on search feature. I installed elasticsearch - here all things are working. In base.html and under url 127.0.0.1:8000 - I have form to search and I would like to keep this form here. On another hand I have search app with view, url, template - under url 127.0.0.1:8000/search/ - search is working here. To solve this problem - search on main page and redirect on site with results I was trying to use action attribute in django form. form in base.html <form action="{% url 'search:search' %}" method="post"> {% csrf_token %} <div class="input-group"> <input type="text" class="form-control" id="q" {% if request.GET.q %}value="{{ request.GET.q }}"{% endif %} name="q" placeholder="Search"> <div class="input-group-append"> <button class="btn btn-outline-primary" type="button">GO</button> </div> </div> </form> view in search app def search(request): q = request.GET.get('q') if q: posts = PostDocument.search().query('match', title=q) else: posts = '' return render(request, 'search/search.html', {'posts': posts}) template with results {% extends 'base.html' %} {% block content %} {% for p in posts %} <a href="#">{{ p.title }}</a> {% endfor %} {% endblock content %} {% block sidebar %}{% endblock sidebar %} -
No module named django, but django is installed - miniconda has interfered with path?
So to clarify, I had already got Django to work. The main thing I had done between installing Django and having this problem is that I installed miniconda3 and MySQLdb. I'm running Python 3.7.1, pip 18.1 and as far as I know should have Django 2.1.4. From /Users/me I run: python3 -m django --version and I get: /Users/me/miniconda3/bin/python3: No module named django From this I can see that the path seems to have been changed to miniconda, and I'm not sure how that has happened. If I run: pip3 install Django It then tells me: Requirement already satisfied: Django in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (2.1.4) Does anyone have either any idea of what could have happened and how to rectify it?