Posts

Showing posts with the label django

creating a custom template tags in django

creating a custom template tags in django I am new to Django and I am trying to create custom tags in django my custom tag file templatetag/custom_tag.py templatetag/custom_tag.py from django import template from model_file.models import my_Model register = template.Library() @register.simple_tag def get_custom_tag_fn(): return my_Model.objects.all() my html file {% load custom_tag %} {% get_custom_tag_fn as queries %} {% for query in queries %} {{query.json_my_model_data}} {% endfor %} I am not getting any output or error from this code. Can anyone point where I went wrong. for extra information my model.py looks like model.py from django.db import models from jsonfield import JSONField class my_Model(models.Model): json_my_model_data = JSONField() Are there any instances in my_Model ? – Willem Van Onsem Jul 1 at 9:43 ...

The view didn't return an HttpResponse object. It returned None instead

The view didn't return an HttpResponse object. It returned None instead I have the following simple view. Why is it resulting in this error? The view auth_lifecycle.views.user_profile didn't return an HttpResponse object. It returned None instead. The view auth_lifecycle.views.user_profile didn't return an HttpResponse object. It returned None instead. """Renders web pages for the user-authentication-lifecycle project.""" from django.shortcuts import render from django.template import RequestContext from django.contrib.auth import authenticate, login def user_profile(request): """Displays information unique to the logged-in user.""" user = authenticate(username='superuserusername', password='sueruserpassword') login(request, user) render(request, 'auth_lifecycle/user_profile.html', context_instance=RequestContext(request)) ...

Django PUT TestCase fails if client initialised in setUpTestData() but passes if client initialized in setUp()

Django PUT TestCase fails if client initialised in setUpTestData() but passes if client initialized in setUp() I am writing tests where every test case passes except the PUT from django.test import TestCase from rest_framework.test import APIClient class ViewTestCase(TestCase): @classmethod def setUpTestData(cls): cls.client = APIClient() def setUp(self): """setUp() runs before every single test method.""" self.user_data = {'first_name': "John", 'last_name': "Doe", 'email_id': "john@doe.com", 'phone_number': "987654321", 'is_verified': False} self.response = self.client.post( reverse('create'), self.user_data, format='json') def test_api_can_update_user(self): user = User.objects.get() changes = {'first_name': "Johnny"} ...

NoReverseMatch Django url issue

NoReverseMatch Django url issue I am trying to implement a typical url in my django project however i keep getting the error meassage. I have checked my urls, views and html code where i have passed in the KWARGS. I have no clue what went wrong here please help? The home.html uses user_profile_detail in the template userprofile/home.html <div class="sidebar-fixed position-fixed side_nav_bar "> <a class="logo-wrapper waves-effect"> <img src="/" class="img-fluid" alt=""> </a> <div class="list-group list-group-flush"> **<a href="{% url 'userprofile:dashboard' user_profile_detail.slug %}" class="list-group-item {% if request.path == dashboard %}active{% endif %} waves-effect"> <i class="fa fa-pie-chart mr-3"></i>Dashboard </a>** <a href="{% url 'userprofile:profile' use...

How to enable frontend editing in Django CMS?

How to enable frontend editing in Django CMS? How exactly do I enable front end editing in Django CMS 3.5.2? I added this to the top of my template: {% load cms_tags menu_tags sekizai_tags static %} and I added {% placeholder "content" %} to the body. This works in the sense that I can use it in the structure toolbar but it doesn't show up as an editable field when I hover the mouse over it. I don't want to use {% render_model ... %} as I'm not creating a new model. I know how to use Django but its not helping me much here as DjangoCMS doesn't make it obvious what variables are passed into the template. Please, How do I go about this? Have you remembered to include {% cms_toolbar %} straight after the <body> tag? – markwalker_ Jul 1 at 10:57 {% cms_toolbar %} <body> ...

static files not loading only on django admin page

static files not loading only on django admin page This is on a production server with DEBUG = False. My static files will load on the home page but not the admin page. It gives me a error 404 in the browser console. This only happens on the admin page. I've checked to make sure that the .css files are in the specified directory's and they are along with the code inside them. NOTE: The same server and file structure was working earlier. I've tried almost everything I can think of any help would be greatly appreciated! STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = '/home/django/django_project/django_project/static/' STATIC_URL = '/static/' Did you collectstatic ? – Cole Jul 1 at 2:26 collectstatic Yes, I've also tried rebooting and restarting ngi...

Django persist ModelMultipleChoiceField selections

Django persist ModelMultipleChoiceField selections I have a ModelMultipleChoiceField that allows a user to select one or more of a set of my "community" model (akin to a user joining a subreddit). When the user reopens the page to select communities, there are no checkboxes on the fields that the user has selected before. I would like to make it so that previously selected communities stay with check boxes, and therefore when the user hits submit their previous choices won't be forgotten if they don't reselect the previous choices. Here is my form: class CustomChoiceField(forms.ModelMultipleChoiceField): def label_from_instance(self, obj): return obj.name class CommunitySelectForm(forms.ModelForm): community_preferences = CustomChoiceField(queryset=Community.objects.all(), widget=forms.CheckboxSelectMultiple) class Meta: model= UserQAProfile fields = ['community_preferences'] And here is my template: <div class="col-...

Django MultipleChoiceField not showing saved choices

Django MultipleChoiceField not showing saved choices This is what my form looks like. class DecisionMadeForm(forms.ModelForm): option = forms.MultipleChoiceField(required=False, label = "Which option(s) did you choose? (Please check ALL that apply)") class Meta: model = Decision_Made fields = ('option', ) def __init__(self, *args, **kwargs): dec_id = kwargs.pop("dec_id") choicelist = kwargs.pop("choicelist") super(DecisionMadeForm, self).__init__(*args, **kwargs) instance = getattr(self, 'instance', None) query = Solution_Options.objects.filter(dec_id = dec_id, archived = 'N').values_list('option', flat=True).distinct() query_choices = [(id, id) for id in query] self.fields['sol_option']=forms.MultipleChoiceField(choices=query_choices, required=False, widget=forms.CheckboxSelectMultiple,label="Which choice did you make?") ...

Redirect with get_context_data in generic detailview django

Redirect with get_context_data in generic detailview django I have this view where i needed two models Book and UserFav so I used context for that: class BookDetailView(LoginRequiredMixin, generic.DetailView): model = Book template_name = 'book_detail.html' def get_context_data(self, **kwargs): context = super(BookDetailView, self).get_context_data(**kwargs) context.update({ 'fav_list': UserFav.objects.filter(user=self.request.user) }) return context and another view function def favorite(request, pk): book = get_object_or_404(Book, pk=pk) fav, created = UserFav.objects.get_or_create(user=request.user) fav.favorites.add(book) return render(request, 'book_detail.html', {'book': book}) form for the favourite function <form action="{% url 'favorite' book.id %}" method="post" style="display: inline;"> {% csrf_token %} <button type="subm...

django NoReverseMatch Exception

django NoReverseMatch Exception I'm getting the following error while using hyperlink in Django. Error : django.urls.exceptions.NoReverseMatch: 'mywebapp' is not a registered namespace django.urls.exceptions.NoReverseMatch: 'mywebapp' is not a registered namespace mywebapp/template/about.html .. <body> <a href="{% url 'mywebapp:home' %}">Click here</a> Hello World!!!<p>Today is {{today}}</p> mywebapp/template/home.html .. <h4>Homepage.</h4> settings.py .. INSTALLED_APPS = [ ... 'mywebapp'#new ... ] Make sure you have app_name='home' in your mywebapp/urls.py . If that doesn’t solve the problem, then you need to show your urls.py . – Alasdair Jun 30 at 20:20 app_name='home' mywebapp/urls.py urls.py ...

Python 3.7, Failed building wheel for MySql-Python

Python 3.7, Failed building wheel for MySql-Python I am new to python and I am trying django framework that involves some MySql and ran into this error when try to do pip install mysqlclient and down the lines of cmd messages I got this. pip install mysqlclient Failed building wheel for mysqlclient Running setup.py clean for mysqlclient Failed to build mysqlclient Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... error Complete output from command c:usersronanl~1envspy1scriptspython.exe -u -c "import setuptools, tokenize;__file__='C:\Users\RONANL~1\AppData\Local\Temp\pip-install-pkbqy3t3\mysqlclient\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('rn', 'n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:UsersRONANL~1AppDataLocalTemppip-record-moxwf7luinstall-record.txt --single-version-externally-managed --compile --install-headers c:users...