Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding multiple Date Fields in Django model
I am trying to add a field that would let me add multiple show dates in a Django Model. Sometimes the show date will contain 3 dates, sometimes 1 or sometimes 7. How am I able to add this in a model and have it so I can add multiple dates in the Django admin? -
S3 upload fails in production (Python)
I'm trying to upload an XML file to S3 in my Django app. I have tried tinys3, boto3, and boto original flavor. tinys3 worked like a charm in localhost, but if I'm even importing the file when I load it with Elastic Beanstalk I get an error much like what I get from boto3 when I do the same (except boto3 lets me get as far as launching the server and initiating the xml upload from the client): invalid syntax (_base.py, line 381) Boto original doesn't work at all. I definitely need the ability to upload XML's dynamically to S3. No idea why this won't work. -
AJAX for adding product from a page of multiple products not working in Django templates
I have a template in Django having multiple products for a user to add to cart. The code for the template is below. {% for object in fruits_and_vegetables %} <div class="col-sm-3"> <form class = "submit-form" id = "{{ object.id }}" method="GET" action="{% url 'my_virtual_supermarket_products:my_virtual_supermarket_cart' %}"> <img src="{{ object.image.url }}" width="120" height="120"> <h5 style="color:black">{{ object.name }}</h5> <h5 style="color:black "><i class="fa fa-eur" aria-hidden="true"> {{ object.price }}</i> </h5> <input type="hidden" name="item" value ={{ object.id }}> <input class="form-group" type="number" name="qty" value="1" style="width:25%;text-align: center"/> <input type="submit" class="btn btn-primary submit-btn" id = "{{ object.id }}" value = "Add to cart"> </form> </div> {% endfor %} I am trying to make an AJAX call, so upon adding products to cart the page doesn't need to be refreshed. My jquery code looks like this <script> {% block jquery %} $(".submit-btn").click(function (event) { event.preventDefault(); var formData = $(".submit-form").serialize(); console.log(formData) }); {% endblock %} </script> When I console log the formData, it basically shows me all the products with their item id and quantity. Below is how my console log looks like item=1&qty=1&item=3&qty=4&item=7&qty=1&item=9&qty=1&item=10&qty=1&item=26&qty=1&item=27&qty=1&item=31&qty=1&item=32&qty=1&item=2&qty=1&item=13&qty=1&item=18&qty=1&item=25&qty=1&item=4&qty=1&item=8&qty=1&item=11&qty=1&item=19&qty=1&item=20&qty=1&item=21&qty=1&item=23&qty=1&item=24&qty=1&item=6&qty=1&item=14&qty=1&item=15&qty=1&item=16&qty=1&item=22&qty=1&item=29&qty=1&item=5&qty=1&item=12&qty=1&item=17&qty=1&item=28&qty=1&item=30&qty=1 How can I get only the relevant product chosen through the serialize method ? -
Django Reverse Error: NoReverseMatch at
Hello StackOverFlow Members, before i get down to the point, let me retrace my thought/process here to help further slim down my issue. When i click a location object in "location_tree.html" it would redirect me to a new page, "accounts/location/(?P\d+)/" or "location", displaying the location name and its type. From the very same page, the name would be a hyperlink to another page with more details about the "location". But when i attempt to click the name, it redirects me to this error: NoReverseMatch at /accounts/location/2/ Reverse for 'continent' with keyword arguments '{u'pk': 2}' not found. 1 >pattern(s) tried: ['accounts/location/(?>P\d+)/location_continent/(?P\d+)/'] Some key things to note, i am using python2.7. Here is my working code, App/models.py: class Location(models.Model): title = models.CharField(max_length=255) location_type = models.CharField(max_length=255, choices=LOCATION_TYPES) parent = models.ForeignKey("Location", null=True, blank=True, related_name="parent_location") def __unicode__(self): return self.title class Continent(models.Model): title = models.CharField(max_length=255) location = models.OneToOneField(Location, on_delete=models.CASCADE, primary_key=True) is_an_island = models.BooleanField(default=False) def __unicode__(self): return self.location.title App/views.py: def view_page_location(request, location_id): location = Location.objects.get(id=location_id) if location.location_type == 'Continent': continent = Continent(location=location, is_an_island=False) return render(request, 'accounts/location.html', {'location':location, 'continent':continent}) def view_continent(request, pk): get_continent=get_object_or_404(Continent, pk) return render(request, 'accounts/location_continent.html', {'get_continent':get_continent}) Project/urls.py: from App.views import * url(r'^accounts/location/(?P<location_id>\d+)/', view_page_location, name='location'), url(r'^accounts/location/(?P<location_id>\d+)/location_continent/(?P<pk>\d+)/', view_continent, name='continent'), Templates, location_tree.html: {% for child in locations %} {% … -
How to make migrations only one app inside project using django
I have the follow project structure: MyProject |--myBaseApp | |--migrations | |--__init__.py | |--models.py | |... |--myClientApp | |--migrations | |--__init__.py | |--models.py | |... |--myProject | |--__init__.py | |--settings.py | |--urls.py | |... |--manage.py |... I can import to myClientApp/models.py the models.py from myBaseApp, but when I use the commands on terminal mode: python manage.py makemigrations python manage.py migrate myClienteApp The Django creates, on data base, all tables from models.py, both myClienApp/models.py and myBaseApp/models.py. I'd like to make migrate only the models.py from myClienApp/models.py. It's possible? Or do I need to create other project? -
Learning to work with HTTP requests in Python 3
I would first kindly like to express my gratitude to all people that are taking the time to read this post and/or respond to it! As a novice "developer" I only recently found out about this website and the professional highly skilled members that are present here impress me in every question I read. So thank you for that! For my question; I recently started with python (3.6 in PyCharm Professional) and am in the process of building an web application on the Django framework (although right now I am exploring the Flask framework). My problem is that I can't seem to get my head around HTTP Requests (aka, making my front-end of the web application connect to my serverside and server-hosted Python scripts). I read the Python and Django documentation and watched multiple video tutorials on youtube that were well reviewed but still can't wrap my head around it. What I am looking for is a link to a clear description with preferably a tutorial that focuses solely on HTTP requests so I can make myself familiar with it. Does anybody knows a good source or has had the same problem in the past and overcame it? I would … -
trouble iterating through dictionary keys and values in django template
I am trying to iterate through a context dictionary in a template in django. So far I've been unsuccessful and I'm not understanding what it is wrong. This is my view: def main_view(request): cat_dict = {'Other': 0, 'Meeting': 0, 'Project 1': 0, 'Project 2': 0, 'Project 3': 0, 'Project 4': 0, 'Collaboration 1': 0, 'Collaboration 2': 0, 'Collaboration 3': 0, 'Process 1': 0 } my_dict = gCalScriptMain.gCalScript(cat_dict) return render(request, 'gCalData/gCalData_main.html', context=my_dict) Instead, this is my template: {% extends "base.html" %} {% block content %} <div class="jumbotron index-jumbotron"> <h1 id="main-title">gCalData</h1> <ul style="color:white"> {% for k,v in my_dict.items %} <li>{{ k }}: {{ v }}</li> {% endfor %} </ul> </div> {% endblock %} But I get nothing (not even an error). The only thing I can do is retrieve a single value if I put this in the template: {% extends "base.html" %} {% block content %} <div class="jumbotron index-jumbotron"> <h1 id="main-title">gCalData</h1> <p style="color:white">{{ Other }}</p> </div> {% endblock %} -
Django pass variables to form_class
I am trying to figure out how to access fields from a Model that is used as a ForeignKey within the Model that the forms are querying. Each Room has a form where the user selects a Layout from a dynamic list of possible Layout objects. 1—The HTML forms/room/update/layouts.html <form class="layouts__form form-horizontal" action="" method="post" enctype="multipart/form-data"> <fieldset class="form__options"> {% csrf_token %} {% for field in form.layout %} <div class="layouts__layout"> {{ field.tag }} {{ field.choice_label }} <label for="value_{{ forloop.counter0 }}"> <div class="layouts__layout__thumbnail layouts__layout__thumbnail--{{ field.choice_label }}" style="background-image: url('### (I WOULD LIKE TO LOAD 'Layout.thumbnail' HERE) ###');"></div> </label> </div> {% endfor %} <div class="form__submit"> <button type="submit">Submit</button> </div> </fieldset> </form> 2—The form is being called by this in views.py: class LayoutView(UpdateView): model = Room form_class = LayoutForm template_name = 'forms/room/update/layouts.html' 3—Which is being created by this in forms.py: class RoomLayoutForm(forms.ModelForm): layout = forms.ModelChoiceField( widget=forms.RadioSelect(attrs={'type': 'radio', 'id': 'value',}), queryset=Layout.objects.all(), required=False, empty_label=None) class Meta: model = Room fields = ['layout'] 4—Which uses the Room model from: class Room(models.Model): title = models.CharField(max_length=200, blank=True) layout = models.ForeignKey(Layout, related_name='template_selected', blank=True, null=True) def __str__(self): return self.title 5—Which takes one of the Layout models as a ForeignKey defined here: class Layout(models.Model): title = models.CharField(max_length=200) ... padding_top = models.IntegerField(blank=False, default=0) ... thumbnail = … -
django "MyModel.user" must be a "User" instance
helloo I have in DJANGO app two functions where I want to work in my views.py the second function need the output from the first function to work. my views.py(before) : @login_required(login_url="login/") def app_details(request,slug): if request.method == "POST": b = request.user.id test = request.POST.get('index') test_path_export=test+'add/path' my_task_name(test,test_path_export) save_alg(request.user,test_path_export) return render(request, 'details.html'............................... my_function_name.py def my_function_name(input1,output1): .................................. .................................. return save_alg(user_id,output1) myalg.py from django.contrib.auth.models import User def save_alg(user_id,input1): instance = MyModel.objects.create(user=user_id, field1=input1) .................................. .................................. instance.save() and all work functions(my_task_name,save_alg) works fine ... now I want to create one function from this two functions to work in the some function because I want to add async tasks using celery in the future and if I have one function is very easy to use .delay. I change my_function_name.py to: def my_function_name(user_id,input1,output1): .................................. .................................. return save_alg(user_id,output1) and second try to def my_function_name(user_id,input1,output1): .................................. .................................. save_alg(user_id,output1) and in my views.py: @login_required(login_url="login/") def app_details(request,slug): if request.method == "POST": b = request.user.id test = request.POST.get('index') test_path_export=test+'add/path' my_task_name(request.user,test,test_path_export) return render(request, 'details.html'............................... error message in line instance = MyModel.objects.create(user=user_id, field1=input1) : self.field.remote_field.model._meta.object_name, ValueError: Cannot assign "28": "MyModel.user" must be a "User" instance. I have add : from django.contrib.auth.models import User import user in all python files. any idea how to fix this … -
Numeric value[i] in list Python
In Django template I want get data from some list, example: list pages as data(doc in couch_db): { "_id": "someone", "_rev": "someone", "is_active": true, "priority_questions": 1, "answer_3": "test-data3", "answer_2": "test-data2", "answer_1": "test-data1", "answer_0": "test", "ask_3": "test-ask3", "ask_2": "test-ask2", "ask_1": "test-ask1", "ask_0": "test-ask", "title": "new-test", "extra_field_count": "4", "priority_3": 4, "priority_2": 3, "priority_1": 3, "priority_0": 1, "type": "help" } template: {% for page in pages %} <div class="box"> {{ page.title }} {% for i in page.extra_field_count %} {{ page.ask_<em>[i]</em> }} {{ page.answer_<em>[i]</em> }} {% end_for %} {% end_for %} Please help me, if you can -
Python Social Auth authenticating users to wrong accounts
For some reason users while using Facebook to oath, the user will auth as random users. When I looked into the UserSocialAuth table there was one user who had over 700 UserSocialAuth records, (there were a dozen users with over a hundred Facebook UserSocialAuth instances). At first I thought this might be a symptom of some Facebook users not having emails (emails are our username). I don't think this is the issue any more, because then they would all be authenticating to the same user. Users are reporting being connected to different users. The pipelines we're using is this SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.user.create_user', 'apps.accounts.pipeline.validate_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) The custom functions in the pipeline are these: def validate_user(strategy, user, response, details, is_new=False, *args, **kwargs): if not user.validated_at: user.validated_at = timezone.now() user.save() We are using the email field as our username, if that matters. We're using Django==1.10 social-auth-app-django==1.2.0 social-auth-core==1.4.0 -
how to get inverse object relation of object in django
I have the following model: class Employee(models.Model): user = models.OneToOneField(User, blank=True, null=True) company = models.ForeignKey('companies.Company', related_name='company', blank=True, null=True) brand = models.OneToOneField('companies.Brand', related_name='brand', blank=True, null=True) I try to get the employee from the Brand like this: attendees = Brand.objects.filter(pk=2) for a in attendees: print a.employee I get the error: 'Brand' object has no attribute 'employee' How can I get the employee from the brand? Thanks -
Django TemplateDoesNotExist : music/index.html
Ok i have this problem in my code when i run the server and go to the http://127.0.0.1:8000 it's run ok but the problem is ( i have a project called website and an app called music ok when i go to the http://127.0.0.1:8000/music it's tell me this Exception Type : TemplateDoesNotExist Exception Value: music/index.html my view.py from django.shortcuts import render from django.http import HttpResponse from .models import Album enter code here enter code here def index(request): all_albums = Album.objects.all() context = { 'all_albums': all_albums } return render(request, 'music/index.html',context) and this is what my server says enter image description here sorry about my English so bad -
Add blog posts without category
I want to be able to add some blog posts with categories and some without categories in django. with this models django admin won't let me add blog posts without a category. Thanks. from django.db import models from django.db.models import permalink class Blog(models.Model): title = models.CharField(max_length=100, unique=True) slug = models.SlugField(max_length=100, unique=True) body = models.TextField() pub_date = models.DateField(db_index=True, auto_now_add=True) # Many-to-one relationship. category = models.ForeignKey('blog.Category') class Category(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(max_length=100) -
Object matching query does not exist in Test case
i have strange problems I have next code ` def test_profile(self): profile = Profile.objects.get(pk=3) request = self.factory.get(reverse('user-profile', kwargs= {'username': profile.username} )) force_authenticate(request, user=profile, token=self.token.key) view = ProfileView.as_view() #API view look field username response = view(request, profile.username) print(response.status_code) print(response.data)` Of course i have def setUp which have self.token & self.factory When i ran test i received error profiles.models.DoesNotExist: Profile matching query does not exist. but it 100% exist is test DB. Proof: 1)I can call print(profile.username) 2)Profile.objects.get(pk=3) will be error if it doesn't exist How know what is the problem? -
Timeout when reading response headers from daemon process 'swpdoc': /var/www/swpdoc/swpdoc/wsgi.py
I am getting this error radomaly (not always) Timeout when reading response headers from daemon process 'swpdoc': /var/www/swpdoc/swpdoc/wsgi.py Here is my httpd.conf WSGIScriptAlias / /var/www/swpdoc/swpdoc/wsgi.py WSGIApplicationGroup %{GLOBAL} <Directory /var/www/swpdoc/swpdoc> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess swpdoc python-home=/var/www/swpdoc/venswpdoc python- path=/var/www/swpdoc WSGIProcessGroup swpdoc Any help. Loading the index page taking so long and sometime i get timeout errors. I am also using whoosh -
AttributeError: 'property' object has no attribute 'copy' - while trying to get object list in Django Rest
To practice my Django skills i try to make simple module that should work more or less like Admin site in Django. It should gather all Models from Application, list them and show every object from each Model. i try to do is using Django Rest Framework. Here is my views.py. I have 2 views. The api_root listens all models but it also sends params-models_names to another view 'model_view'. The ModelViewSet should list all objects from particular model. class ModelsViewSet(viewsets.ModelViewSet): def get_serializer(self, *args, **kwargs): serializer_name = '{model_name}Serializer'.format( model_name=self.kwargs.get('name').split(".")[1] ) return getattr(serializers, serializer_name) def get_model(self): """methods return model based on name kwargs :return: """ return apps.get_model(self.kwargs.get('name')) def get_queryset(self): return self.get_model().objects.all() def get_object(self): return self.get_model().objects.get(pk=self.kwargs.get('pk')) @api_view(['GET']) def api_root(request, format=None): return Response([reverse( viewname='model_view', kwargs={'name': i._meta.label}) for i in apps.get_models()]) Here is my serializers.py. In this file serializers classes are dynamically build. Each class is built on the basis of the model from django.apps. from django.apps import apps from rest_framework import serializers from admin_site import serializers as m from . import models app_models = apps.get_models() for item in app_models: name = "{}Serializer".format(item.__name__) class Meta(type): model = item fields = '__all__' m.__dict__[name] = type(name, (serializers.ModelSerializer,), {}) m.__dict__[name].__metaclass__ = Meta And finally here is my my_app.urls.py … -
Multi DB test - Create a dynamic ChoiceField for admin interface?
I am testing a multi-database setup and need to populate a ChoiceField in the admin interface. I need a pull down for the movie_title field in movies.MovieEvent populated from the title field of calendar_app.Event via the foreign key in calendar_app.EventOccurence. With a foreign key in play I can't make movie_title a foreign key to the EventOccurence model so I'm attempting to pull the records and then create a tuple to populate the pull down. Here's what I have, this throws ValueError, not enough values to unpack (expected 2, got 1): These models are routed to database #1: # calendar_app/models.py class Event(models.Model): title = models.CharField(max_length=100) tags = models.ManyToManyField(Tag) ... class EventOccurence(models.Model): event = models.ForeignKey(Event, related_name='event') event_date = models.DateField() ... This Model is routed to database #2: #movies/models.py class MovieEvent(models.Model): movie_title = models.CharField(max_length=80) ... Admin: #admin.py from calendar_app.models import EventOccurrence ... class MovieEventAdminForm(forms.ModelForm): movie_events = EventOccurrence.objects.filter(Q(event__tags__slug__exact='movie')).distinct() y = ", (".join(str("'" + x.event.title + "', '" + x.event.title + "')") for x in movie_events) movie_choices = str("(" + "(" + y + ")") movie_title = forms.ChoiceField(choices=movie_choices) class Meta: model = MovieEvent fields = ( ... 'movie_title', ... ) class MovieEventAdmin(admin.ModelAdmin): form = MovieEventAdminForm The above throws the ValueError but when test my tuple … -
Django - new style middleware process_response
I'm using the new style middleware in Django, and for some reason, it never gets to the 'process_response' part. If I understand correctly, it should occur after the response = self.get_response(request) in __call__ function. But it never gets to the code beyond that line. What could be the reason? This is how my middleware is defined: class GlobalThreadVarMiddleware(object): _threadmap = {} def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. self._threadmap[_thread.get_ident()] = {} self._threadmap[_thread.get_ident()]['data_manager'] = DataManager() response = self.get_response(request) # Code to be executed for each request/response after # the view is called. current_data_manager = self.get_current_data_manager() current_data_manager.trigger_events() del self._threadmap[_thread.get_ident()]['data_manager'] return response @classmethod def get_current_data_manager(cls): return cls._threadmap[_thread.get_ident()]['data_manager'] -
Django Backblaze B2 Storage how to automaticly upload files
I'm deploying django and for static files deployment I used Backblaze B2 Storage service. I used a custom file storage wich integrate with b2. But, I need to upload every file manually to the cloud, and I'm wondering if exists a way, at the time to do python manage.py collectstatic, to upload every file processed by collecstatic command, and this way, always be in sync with cloud. -
Inner Join in Django
I have two tables front_employee (Employee model in Django) +-----------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-----------------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | order | int(11) | NO | | NULL | | | name | varchar(100) | YES | | NULL | | | position | varchar(100) | YES | | NULL | | | description | longtext | YES | | NULL | | | employee_img_id | int(11) | NO | MUL | NULL | | | language_id | int(11) | NO | MUL | NULL | | +-----------------+--------------+------+-----+---------+----------------+ And front_employeepicture (EmployeePicture in Django) +-------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | order | int(11) | NO | | NULL | | | img | varchar(100) | YES | | NULL | | +-------+--------------+------+-----+---------+----------------+ I would like to perform this query: SELECT a.id, a.name, b.img FROM front_employee a INNER JOIN front_employeepicture b ON a.employee_img_id = b.id For now I have context['employee'] = Employee.objects.all().order_by('order') And I tried something like context['employee'] = Employee.objects.select_related('EmployeePicture') Without … -
how to access database model fields of parent model linked as e.g. Class->School->User?
I am fairly new to programming languages, django and database models. So my question is simple I have 3 models in models.py as class UserProfileInfo(models.Model): # create relationship with built-in user in admin user = models.OneToOneField(User) portfolio_site = models.URLField(blank=True) class School(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=256) principal = models.CharField(max_length=256) location = models.CharField(max_length=256) class Classroom(models.Model): school = models.ForeignKey(School, on_delete=models.CASCADE) class_name = models.CharField(max_length=256) desc = models.CharField(max_length=256) And I want to access 'id' from User model. I have tried using def ClassroomView(request): classroom_list = Classroom.objects\ .filter(school__id=request.session.get('user_id','0'))\ .filter(user__id=1).values() class_dict = {'class_records': classroom_list} return render(request, 'basic_app/classroom_list.html', context=class_dict) And it gives the following error: FieldError at /basic_app/class/ Cannot resolve keyword 'user' into field. Choices are: class_name, desc, id, school, school_id Is there any way that i can access the fields of User model from Classroom model since it is linked by foreign key as Classroom->School->User Please tell me if I am doing something wrong here any insights and solutions are appreciated!! -
Creating a vulnerable Django search bar
I want to create a vulnerable search bar and have done everything but unfortunately, the search function doesn't show any result when I press submit. But terminal shows successful, "POST /injection/ HTTP/1.1" 200 596 views.py @csrf_exempt def search_form(request): if 'searchField' in request.POST: query= "SELECT * FROM injection_search WHERE injection_search.name LIKE '%searchField%'" print(query) item = search.objects.raw(query) else: item = search.objects.all() return render(request, 'home.html', {'item' : item}) template/home.html {% load static %} <link href="{% static 'css/style.css' %}" rel="stylesheet"></link> <h1 class="page-header">INJECTION</h1> <form action="" method="POST"> <input type="text" name="searchField" id="searchField" placeholder="search trainers.."> <button type="submit">Find</button> </form> <h1> Search Page </h1> <h3> Injection demo</h3> <div class="shopping-container"> <table border="3" cellspacing="0" cellpadding="10"> <tbody> <tr> <th>Title</th> <th>Description</th> <th>Quantity</th> </tr> <!--{% for search in item %}--> <tr> <td>{{ search.name}}</td> <td>{{ search.description }}</td> <td>{{ search.price}}</td> </tr> <!--{%endfor%}--> </tbody> </table> </div> model.py app_name = 'injection' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^injection/$', views.search_form, name='search_form'), ] -
Get reverse model foreign key object for inherited object
I have the following model with a reference an object and an object it inherits from: class Employee(models.Model): user = models.OneToOneField(User, blank=True, null=True) entity = models.ForeignKey('companies.Entity', blank=True, null=True) brand = models.OneToOneField('companies.Brand', related_name='brand', blank=True, null=True) class Entity(models.Model): name = models.CharField('Name', max_length=255, db_index=True) class Brand(Entity): company_name = models.CharField(max_length=128, blank=True, null=True) The problem is when I try to reference the inverse relationship, I can't access the Brand only the Entity. I want to get the employee associated with a brand. I tried this: brands = Brand.objects.filter(pk=2) for b in brands: print b.employee_set.all().query It outputs: SELECT * FROM `employee` WHERE `employee`.`entity_id` = 2 I want it to output: SELECT * FROM `employee` WHERE `employee`.`brand_id` = 2 -
No Reverse Match error in Django
New to Django and stuck on this error. My template was rendering correctly. The only change I made was adding a '1/0' in my views.py file to simulate a breakpoint. And now the template will not render when I remove it. urls.py from django.conf.urls import url from django.shortcuts import redirect from django.views.decorators.csrf import csrf_exempt from django.contrib.auth.views import login, logout from app.views import send_morsel, start_hunt, MorselList, MorselDetailView,\ register, create_morsel, HomePageView, FAQPageView, AboutPageView,\ newsletter_signup, edit_morsel app_name = 'app' urlpatterns = [ url(r'^$', HomePageView.as_view(), name='home'), url(r'^morsels/$', MorselList.as_view(), name='morsel_list'), url(r'^morsels/send/$', send_morsel, name='morsel_send'), url(r'^morsels/(?P<morsel_id>[0-9])/start_hunt/$', start_hunt, name='start_hunt'), url(r'^register/', register, name='register'), url(r'^faq/$', FAQPageView.as_view(), name='faq'), url(r'^about/$', AboutPageView.as_view(), name='about'), url(r'^morsels/create/$', create_morsel, name="create_morsel"), url(r'^morsels/(?P<morsel_id>[0-9])/edit/$', edit_morsel, name='edit_morsel'), url(r'^morsels/(?P<pk>[0-9])/display/$', MorselDetailView.as_view(), name='morsel_detail'), url(r'^newsletter_signup/$', newsletter_signup, name='newsletter_signup') ] morsel_list.html {% extends "app/base.html" %} {% load bootstrap3 %} {% bootstrap_css %} {% bootstrap_javascript %} {% bootstrap_messages %} {% block content %} <h2>Morsels</h2> {% if user.is_authenticated %} <p>hello</p> <p>welcome {{ user.username }}</p> <p><a href="/logout">Logout</a></p> {% else %} <p><a href="/login">Login</a></p> <p><a href="/app/register">Register</a></p> {% endif %} <ul> {% for morsel in object_list %} <li>{{ morsel.name }} <a href="{%url 'app:morsel_detail' morsel.id%}">View</a> <a href="{%url 'app:edit_morsel' morsel.id %}">Edit</a> <a href="{%url 'app:start_hunt' morsel.id%}">Send! </a> </li> {% endfor %} </ul> {% if messages %} {% for msg in messages %} {% bootstrap_alert msg.message alert_type=msg.level_tag …