Menu
  • HOME
  • TAGS

Django: get profiles having auth.Group as foreign key

Tag: django,django-templates,django-authentication,django-users

I have an model which uses auth.models.Group as foreign key called Dashboard:

class Dashboard(models.Model):
    d_name = models.CharField(max_length=200)
    d_description = models.CharField(max_length=200)
    d_url = models.CharField(max_length=200)
    d_status = models.CharField(max_length=200)
    owner = models.ForeignKey(Group)

    def __str__(self):return self.d_name

my views.py is:

def custom_login(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect('dashboards')        
    return login(request, 'login.html', authentication_form=LoginForm)

def custom_logout(request):
    return logout(request, next_page='/')

def user(request):
    context = {'user': user, 'groups': request.user.groups.all()}
    return render_to_response('registration/dashboards.html', context,
                              context_instance=RequestContext(request))

and here using this dashboards.html I want to display the dashboards by using the Group_name which i will get as a result of group.name:

{% extends "base.html" %}
{% block content %}
{% if user.is_authenticated %}
    <p>Welcome, {{ request.user.get_username }}. <br/>
    {% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}

<ul>
{% for group in groups %}
    <li>
        <strong>{{ group.name }}<strong> -

            {{ dashboards.d_name }}{% if not forloop.last %},{% endif %}

    </li>
{% endfor %}
</ul>



{% endblock %}

here I have mentioned all the supporting information for my problem, please let me know if there are any solution.

Best How To :

To access the list of Dashboards for the Group use the group.dashboard_set queryset:

{% for group in groups %}
    <li>
        <strong>{{ group.name }}</strong> -
        {% for dashboard in group.dashboard_set.all %}
            {{ dashboard.d_name }}{% if not forloop.last %},{% endif %}
        {% endfor %}
    </li>
{% endfor %}

This queryset is called "backward relationship".

How can I resolve my variable's unexpected output?

django,python-2.7

Remove the comma on your first line of code, this turns it into a tuple optional_message = form.cleaned_data['optional_message'], should be optional_message = form.cleaned_data['optional_message'] ...

Switch Case in Django Template

python,django,django-1.3

There is no {% switch %} tag in Django template language. To solve your problem you can either use this Django snippet, that adds the functionality, or re-write your code to a series of {% if %}s. The second option in code: {% if property.category.id == 0 %} <h4>'agriculture'</h4> {%...

Django: Handling several page parameters

python,django,list,parameters,httprequest

Since, request.GET is a dictionary, you can access its values like this: for var in request.GET: value = request.GET[var] # do something with the value ... Or if you want to put the values in a list: val_list = [] for var in request.GET: var_list.append(request.GET[var]) ...

Django does not render my forms' fields

django,django-models,django-forms,django-templates,django-views

Your form inherits from forms.Form, which does not know anything about models and ignores the Meta class. You should inherit from forms.ModelForm.

Show message when there's no excerpt - Django templates

python,django,django-templates,django-template-filters

Your problem is with your if/else tags. You have this: {{ % if ... %}} ... {{% else %}} ... First off, you need to surround if/else by {% %}, not {{% %}}. Secondly, you don't have an endif. An if/else block should look like this: {% if ... %}...

Is there a way to install django with pip to point to a specific version of python in virtualenv

python,django,pip,virtualenv

Invoke django-admin.py like this python django-admin.py, in your activate virtualenv. Alternatively you can do /path/to/virtualenv/bin/python django-admin.py. The best solution is probably adding a shebang to django-admin.py that looks like #!/usr/bin/env python which should use the python interpreter of your active virtualenv. See http://stackoverflow.com/a/2255961/639054

Display django runserver output from Vagrant guest VM in host Mac notifications?

python,django,osx,notifications,vagrant

Why not run a SSH server on the VM and connect from the host via a terminal? See MAC SSH. Which OS is running on the VM? It should not be too hard to get the SSH server installed and running. Of course the VM client OS must have an...

Get the first image src from a post in django

django,django-templates,django-views

Here's a basic approach you can tweak for your convenience: Add a first_image field to your model: class Blog(models.Model): title = models.CharField(max_length=150, blank=True) description = models.TextField() pubdate = models.DateTimeField(default=timezone.now) publish = models.BooleanField(default=False) first_image = models.CharField(max_length=400, blank=True) Now all you have to do is populate your first_image field on save, so...

DRF Update Existing Objects

django,django-rest-framework

In your view, you need to provide the following: lookup_field -> Most probably the ID of the record you want to update lookup_url_kwarg -> The kwarg in url you want to compare to id of object You need to define a new url in your urls.py file. This will carry...

Django ClearableFileInput - how to detect whether to delete the file

django,django-forms,django-crispy-forms

You shouldn't check the checkbox, but check the value of the file input field. If it is False, then you can delete the file. Otherwise it is the uploaded file. See: https://github.com/django/django/blob/339c01fb7552feb8df125ef7e5420dae04fd913f/django/forms/widgets.py#L434 # False signals to clear any existing value, as opposed to just None return False return upload ...

Create angular page in Django to consume data from JSON

angularjs,django,django-templates

You can add the angular app as a simple template view in Django views.py def index(request): return render(request, 'yourhtml.html', {}) urls.py .... url(r'^your_url/$', views.index), .... Then the index.html file can have your angular code...

How do I loop through a nested context dictionary in Django when I have no idea the structure I will recieve

django,django-templates,django-views

You need to define a custom template tag which returns the type of data. from django import template register = template.Library() @register.filter def data_type(value): return type(value) Then use it inside your template like this: {% for key, value in leasee.items %} <p> {{key}} </p> <ul> {%if value|data_type == 'dict' %}...

How to use template within Django template?

python,html,django,templates,django-1.4

You can use the include tag in order to supply the included template with a consistent variable name: For example: parent.html <div class="row"> <div class="col-md-12 col-lg-12 block block-color-1"> {% include 'templates/child.html' with list_item=mylist.0 t=50 only %} </div> </div> child.html {{ list_item.text|truncatewords:t }} UPDATE: As spectras recommended, you can use the...

How to get simple ForeignKey model working? (a list of class in another class)

django,django-models,django-queryset

You should reverse the foreign key relationship: class HeartRate(models.Model): timestamp = models.DateTimeField('Date and time recorded') heartrate = models.PositiveIntegerField(default=0) exercise = models.ForeignKey(Exercise, related_name='heartrates') class Exercise(models.Model): start_timestamp = models.DateTimeField('Starting time') finishing_timestamp = models.DateTimeField('Finishing time') To get all of the heartrates of an exercise: heartrates = my_exercise.heartrates.all() ...

Django add an attribute class form in __init__.py

python,django,forms,django-forms

You need to assign the field to form.fields, not just form. However this is not really the way to do this. Instead, you should make all your forms inherit from a shared parent class, which defines the captcha field....

Trying to write a unit test for file upload to a django Restless API

python,django,rest,file-upload,request

I tried to fix this but in the end it was quicker and easier to switch to the Django-REST framework. The docs are so much better for Djano-REST that it was trivial to set it up and build tests. There seem to be no time savings to be had with...

Upload to absolute path in Django

django

You should be able to create a different FileSystemStorage instance for each storage location. Alternatively, you could write a custom storage system to handle the files....

django and python manage.py runserver execution error

python,django,manage.py

It looks like you're running against the system version of python on the new laptop, rather than the virtualenv, so it is probably a different version. You can check this by looking at the version of Python on the virtualenv in the old laptop and the new laptop with python...

How can i hook into django migrations for django 1.8

python,django,migration

When migration created, you can manually change the base migration class to your custom subclass with overridden apply method from django.db import migrations class MyBaseMigration(migrations.Migration): def apply(self, project_state, schema_editor, collect_sql=False): for operation in self.operations: """ Examine operation classes here and provide end-user notes """ return super(MyBaseMigration, self).apply(project_state, schema_editor, collect_sql=collect_sql) ...

DjangoCMS 3 Filter Available Plugins

django,django-cms

Remove plugins you don't need from INSTALLED_APPS. Alternatively, in an app after all plugin apps in INSTALLED_APPS in either cms_plugins.py or models.py you can use cms.plugin_pool.plugin_pool.unregister_plugin to remove them from the pool: from cms.plugin_pool import plugin_pool from unwanted_plugin_app.cms_plugins import UnwantedPlugin plugin_pool.unregister_plugin(UnwantedPlugin) ...

Django TemplateDoesNotExist Error on Windows machine

python,django

The solution that worked for me was removing the below piece of code from settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] And adding : TEMPLATE_DIRS = ('C:/Users/vaulstein/tango_with_django_project/templates',) OR Changing the line...

Permission denied Setuptools

python,django,curl,setuptools

You need sudo for the python command to write to /Library/Frameworks...: curl https://bootstrap.pypa.io/ez_setup.py -o - | sudo python ...

Why is Django widgets for TimeInput not showing

django,django-forms,django-templates,django-views

The Django admin uses AdminTimeWidget to display time fields, not the TimeInput widget that you are using in your code. There isn't a documented way to reuse the AdminTimeWidget outside of the Django admin. Getting it to work is very hacky (see the answer on this question, which is probably...

Django test RequestFactory vs Client

django,unit-testing,django-views,django-rest-framework,django-testing

RequestFactory and Client have some very different use-cases. To put it in a single sentence: RequestFactory returns a request, while Client returns a response. The RequestFactory does what it says - it's a factory to create request objects. Nothing more, nothing less. The Client is used to fake a complete...

How to work with django-rest-framework in the templates

json,django,django-templates,django-rest-framework

model.py: class Day(models.Model): date = models.DateField(default=date.today) def get_todo_list(self): return self.day_todo_set.order_by('-id')[:5] class ToDo(models.Model): date = models.ForeignKey(Day, related_name="day_todo_set") name = models.CharField(max_length=100) very_important = models.BooleanField(default=False) finished = models.BooleanField(default=False) In serializers.py class ToDoSerializer(serializers.ModelSerializer): class Meta: model = ToDo field = ('id', 'date', 'name', 'very_important', 'finished') class...

Django MySQLClient pip compile failure on Linux

python,linux,django,gcc,pip

It looks like you're missing zlib; you'll want to install it: apt-get install zlib1g-dev I also suggest reading over the README and confirming you have all other dependencies met: https://github.com/dccmx/mysqldb/blob/master/README Also, I suggest using mysqlclient over MySQLdb as its a fork of MySQLdb and what Django recommends....

upload_to dynamically generated url to callable

python,django,models

It looks like (re-reading your post it's not 100% clear) what you want is a partial application. Good news, it's part of Python's stdlib: import os from functools import partial def generic_upload_to(instance, filename, folder): return os.path.join(instance.name, folder, filename) class Project(TimeStampedModel): name = models.TextField(max_length=100, default='no name') logo = models.ImageField( upload_to=partial(generic_upload_to, folder="logo")...

django 1.8 CreateView Error

python,django

Your SignUpView is not specifying the form it should render, you need to add the form_class attribute. class SignUpView(CreateView): form_class = RegistrationForm model = User template_name = 'accounts/signup.html' ...

sorl-thumbnail: Creating a thumbnail inside a for loop in a template

django,sorl-thumbnail

It looks like your plural are in the wrong spot: {% for post_images in post.sellpostimage_set.all %} should be: {% for post_image in post.sellpostimage_set.all %} post_image = SellPostImage.objects.filter(post=poster_posts) context_dict['post_image'] = post_image should be: post_images = SellPostImage.objects.filter(post=poster_posts) context_dict['post_images'] = post_images or: post_image = SellPostImage.objects.get(post=poster_posts) context_dict['post_image'] = post_image why do you do this...

Django template not found in main project directory error

python,django,templates

If your template is independent of apps, it shouldn't be in your app folder - namespace it accordingly. How do you load your template? Did you setup your templates/staticfolders in your settings.py? Updated For the fresh project you need to configure your settings.py file. Read here, ask away if you...

Django: show newlines from admin site?

python,html,django,newline,textfield

Use the linebreaks template filter.

Django file upload took forever with Phusion Passenger

django,apache,file-upload,passenger

Passenger author here. Try setting passenger_log_level to a higher value, which may give you insights on why this is happening. I don't know which Passenger version you are using, but in version 5, the Passenger request processing cycle looks like this: Apache receives the request. Once headers are complete, it...

Django block inclusion not working. What did I miss?

django,django-templates

Django templates do not use inclusion so much as template inheritance. The idea is you set up a hierarchy of templates, specializing some common thing. For instance: you could have a base.html that has some basic page structure, common to all pages of your website. you could then have a...

Use django to expose python functions on the web

python,django

Typically, as stated by @DanielRoseman, you certainly want to: Create a REST API to get data from another web site Get data, typically in JSON or XML, that will contain all the required data (name and surname) In the REST controller, Convert this data to the Model and save the...

Django REST tutorial DEBUG=FALSE error

python,django,django-rest-framework

This error: File "/tutorial/tutorial/urls.py", line 9, in <module> url(r'^admin/', include(snippets.urls)), NameError: name 'snippets' is not defined occurs because snippets.urls has to be quoted. See the example here: urlpatterns = [ url(r'^', include('snippets.urls')), ] As shown here, you could write something like this: from django.contrib import admin urlpatterns = [ url(r'^polls/',...

Django listview clone selected record

django

I've done this with a simple method in views.py. Simply retrieve the record, blank out its id then save and open it. Something like def create_new_version(request) : record = models.MyDocument.objects.filter(id=request.GET['id'])[0] record.id = None record.save() return http.HttpResponseRedirect(reverse('edit-mydocument', kwargs={'pk':record.id})) where MyDocument is your model and edit-mydocument is your UpdateView. Just call this...

Using .update with nested Serializer to post Image

django,rest,django-models,django-rest-framework,imagefield

As noted in the docs, .update() doesn't call the model .save() or fire the post_save/pre_save signals for each matched model. It almost directly translates into a SQL UPDATE statement. https://docs.djangoproject.com/en/1.8/ref/models/querysets/#update Finally, realize that update() does an update at the SQL level and, thus, does not call any save() methods on...

Callable in model field not called upon adding new object through Django admin

django,django-models,django-admin

Try: when_first_upload = models.DateTimeField(default=datetime.datetime.now) You need the callable itself, not the result returned by it....

Does Django implement user permissions in databases with models?

python,django,orm,django-admin

Django by itself doesn't provide access to the database-level users / groups / permissions, because it doesn't make much sense for a typical web application where all connections will be made with the same database user (the one defined in settings.DATABASES). Note that it's not a shortcoming be really the...

Django: html without CSS and the right text

python,html,css,django,url

Are you using the {% load staticfiles %} in your templates?

How can I fill the table? (Python, Django)

python,django

There are two things that you need to change. In the views.py file, rather than returning 4 different lists, return a single zipped version of the lists like zipped_list = zip(first_list, second_list, third_list, fourth_list) Now this must be passed to the view file that is being rendered. context_dict = {'zipped_list':...

django cannot multiply non-int of type 'str'

python,django

I would use this: def _total_amount(self): req = QuoteRow.objects.filter(quote=self.pk) return sum([i.unit_price * i.quantity for i in req]) It takes one more line but it's clearer to me....